export default {
    props: [ 'kind', 'name', 'token', 'state' ],
    data() {
        return { createDisabled: false, selectedAssets: {} }
    },
    computed: {
        availableAssets() {
            return {
                cluster: ['addons'],
                host: [
                    "kernel",
                    "initrd",
                    "bootstrap.tar",
                    "boot.img.lz4",
                    "boot.iso",
                    "config",
                    "bootstrap-config",
                    "boot.tar",
                    "boot-efi.tar",
                    "boot.img.gz",
                    "boot.img",
                    "ipxe",
                ],
            }[this.kind]
        },
        downloads() {
            let ret = []
            Object.entries(this.state.Downloads)
              .filter(e => { let d=e[1]; return d.Kind == this.kind && d.Name == this.name })
              .forEach(e => {
                let token= e[0], d = e[1]
                d.Assets.forEach(asset => {
                    ret.push({name: asset, url: '/public/downloads/'+token+'/'+asset})
                })
              })
          return ret
        },
        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) => { alert('failed to create link'); this.createDisabled = false })
        },
    },
    template: `<div class="downloads">
  <div class="options">
    <span v-for="asset in availableAssets"><label><input type="checkbox" v-model="selectedAssets[asset]" />&nbsp;{{ asset }}</label></span>
  </div>
  <button :disabled="createDisabled || assets.length==0" @click="createToken">+</button>
  <div><a v-for="d in downloads" target="_blank" :href="d.url">{{ d.name }}</a></div>
</div>`
}