const Downloads = {
    props: [ 'kind', 'name', 'token', 'state' ],
    data() {
        return { createDisabled: false, selectedAssets: {}, msg: null }
    },
    computed: {
        availableAssets() {
            return ({
                host: [
                    "kernel",
                    "initrd",
                    "uki",
                    "bootstrap.tar",
                    "boot.img.gz",
                    "boot.img",
                    "boot.qcow2",
                    "boot.vmdk",
                    "boot.iso",
                    "boot.tar",
                    "bootstrap-config",
                    "config",
                    "config.json",
                    "ipxe",
                ],
            }[this.kind] || [])
        },
        downloads() {
            return Object.entries(this.state.Downloads)
              .filter(e => { let d=e[1]; return d.Kind == this.kind && d.Name == this.name })
              .map(e => {
                const token= e[0];
                return {
                  text: token.substring(0, 5) + '...',
                  url: '/public/downloads/'+token+"/",
                }
              })
        },
        assets() {
            return this.availableAssets.filter(a => this.selectedAssets[a])
        },
    },
    methods: {
        createToken() {
            event.preventDefault()
            this.createDisabled = true

            fetch('/authorize-download', {
                method: 'POST',
                body: JSON.stringify({Kind: this.kind, Name: this.name, Assets: this.assets}),
                headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
            }).then((resp) => resp.json())
              .then((token) => { this.selectedAssets = {}; this.createDisabled = false })
              .catch((e) => { this.msg = 'failed to create link'; this.createDisabled = false })
        },
    },
    template: `
  <h4>Available assets</h4>
  <p class="error" v-if="msg">{{ msg }} <button class="btn-close" @click="msg=null">&times;</button></p>
  <p class="downloads">
    <template v-for="asset in availableAssets">
      <label :class="{selected: selectedAssets[asset]}"><input type="checkbox" v-model="selectedAssets[asset]" />&nbsp;{{ asset }}</label>
      {{" "}}
    </template>
  </p>
  <p><button :disabled="createDisabled || assets.length==0" @click="createToken">Create link</button></p>
  <template v-if="downloads.length">
    <h4>Active links</h4>
    <p class="download-links"><template v-for="d in downloads"><a :href="d.url" target="_blank">{{ d.text }}</a>{{" "}}</template></p>
  </template>`
}
