const ClusterAccess = {
    props: [ 'cluster', 'token', 'state' ],
    data() {
        return {
            accessType: "ssh",
            signReqValidity: "1d",
            sshSignReq: {
                PubKey: "",
                Principal: "root",
            },
            kubeSignReq: {
                CSR: "",
                User:   "",
                Group:  "system:masters",
            },
            downloadSet: null,
            selectedAssets: {},
            loading: false,
            msg: null,
        };
    },
    watch: {
            'kubeSignReq.CSR'(v) {
                if (v && v.includes('BEGIN CERTIFICATE REQUEST')) {
                    fetch(`/public/parse-kube-csr`, {
                        method: 'POST',
                        body: JSON.stringify({ csr: v }),
                        headers: { 'Content-Type': 'application/json' },
                    }).then(r => {
                        if (r.ok) r.json().then(d => {
                            this.kubeSignReq.User = d.user || "anonymous";
                            this.kubeSignReq.Group = d.group;
                        });
                    }).catch(() => {});
                }
            },
        },
    computed: {
        availableAssets() {
            return [
                "kernel",
                "initrd",
                "uki",
                "bootstrap.tar",
                "boot.img.gz",
                "boot.img",
                "boot.qcow2",
                "boot.vmdk",
                "boot.iso",
                "boot.tar",
                "bootstrap-config",
                "config",
                "config.json",
                "ipxe",
            ]
        },
        selectedAssetList() {
            return this.availableAssets.filter(a => this.selectedAssets[a])
        },
        hostCount() {
            return (this.state.Hosts||[]).filter(h => h.Cluster == this.cluster.Name).length
        },
    },
    methods: {
        sshCASign() {
            event.preventDefault();
            this.loading = true; this.msg = null;
            fetch(`/clusters/${this.cluster.Name}/ssh/user-ca/sign`, {
                method: 'POST',
                body: JSON.stringify({ ...this.sshSignReq, Validity: this.signReqValidity }),
                headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
            }).then((resp) => {
                if (resp.ok) {
                    resp.blob().then((cert) => {
                        const url = URL.createObjectURL(cert);
                        const a = document.createElement('a');
                        const parts = this.sshSignReq.PubKey.trim().split(/\s+/);
                        const user = parts.length > 2 ? parts[parts.length - 1] : this.sshSignReq.Principal;
                        a.href = url; a.download = user + '-cert.pub';
                        a.click(); URL.revokeObjectURL(url);
                        this.loading = false;
                    })
                } else {
                    resp.json().then((resp) => { this.msg = 'failed to sign: '+resp.message; this.loading = false })
                }
              })
              .catch((e) => { this.msg = 'failed to sign: '+e; this.loading = false })
        },
        kubeCASign() {
            event.preventDefault();
            this.loading = true; this.msg = null;
            fetch(`/clusters/${this.cluster.Name}/kube/sign`, {
                method: 'POST',
                body: JSON.stringify({ ...this.kubeSignReq, Validity: this.signReqValidity }),
                headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
            }).then((resp) => {
                if (resp.ok) {
                    resp.blob().then((cert) => {
                        const url = URL.createObjectURL(cert);
                        const a = document.createElement('a');
                        a.href = url; a.download = (this.kubeSignReq.User || this.kubeSignReq.Group) + '.crt';
                        a.click(); URL.revokeObjectURL(url);
                        this.loading = false;
                    })
                } else {
                    resp.json().then((resp) => { this.msg = 'failed to sign: '+resp.message; this.loading = false })
                }
              })
              .catch((e) => { this.msg = 'failed to sign: '+e; this.loading = false })
        },
        generateDownloadSet() {
            event.preventDefault()
            this.loading = true; this.msg = null;

            const items = [{
                Kind: "host",
                Name: "c=" + this.cluster.Name,
                Assets: this.selectedAssetList,
            }]

            fetch('/sign-download-set', {
                method: 'POST',
                body: JSON.stringify({Expiry: this.signReqValidity, Items: items}),
                headers: { 'Authorization': 'Bearer ' + this.token, 'Content-Type': 'application/json' },
            }).then((resp) => {
                if (resp.ok) {
                    resp.json().then((set) => { this.downloadSet = set; this.loading = false })
                } else {
                    resp.json().then((resp) => { this.msg = 'failed to generate: '+resp.message; this.loading = false })
                }
            }).catch((e) => { this.msg = 'failed to generate: '+e; this.loading = false })
        },
        readFile(e, onload) {
            const file = e.target.files[0];
            if (!file) { return; }
            const reader = new FileReader();
            reader.onload = () => { onload(reader.result) };
            reader.onerror = () => { this.msg = "error reading file" };
            reader.readAsText(file);
        },
        loadPubKey(e) {
            this.readFile(e, (v) => {
                this.sshSignReq.PubKey = v;
            });
        },
        copyDownloadSetUrl() {
            try {
                navigator.clipboard.writeText(window.location.origin+'/public/download-set?set='+this.downloadSet)
                this.$root.toast('copied!', 'info')
            } catch (e) {
                this.$root.toast('copy failed', 'error')
            }
        },
        loadCSR(e) {
            this.readFile(e, (v) => {
                this.kubeSignReq.CSR = v;
            });
        },
    },
    template: `
  <p>Grant access to:
     <label class="radio"><input type="radio" v-model="accessType" value="ssh" /> SSH</label>
     <label class="radio"><input type="radio" v-model="accessType" value="kube" /> Kubernetes</label>
     <label class="radio"><input type="radio" v-model="accessType" value="download-set" /> Download set</label>
  </p>

  <p>Validity: <input type="text" v-model="signReqValidity"/>
     ← <template v-for="(v,i) in ['5m','1d','1w','1M','1y']">{{ i ? ', ' : ' ' }}<a href="#" @click.prevent="signReqValidity=v">{{ v }}</a></template></p>

  <p class="error" v-if="msg">{{ msg }} <button class="btn-close" @click="msg=null">&times;</button></p>

  <div v-if="accessType == 'ssh'">
    <h4>Grant SSH access</h4>
    <p>User: <input type="text" v-model="sshSignReq.Principal"/></p>
    <p>Public key (OpenSSH format):<br/>
       <span class="text-and-file"><textarea v-model="sshSignReq.PubKey" style="height:3lh"></textarea>
       <input type="file" accept=".pub" @change="loadPubKey" /></span>
    </p>
    <p><button :disabled="loading" @click="sshCASign">{{ loading ? 'signing...' : 'Sign SSH access' }}</button></p>
  </div>

  <div v-if="accessType == 'kube'">
    <h4>Grant Kubernetes API access</h4>
    <p>Certificate signing request (PEM format):<br/>
       <span class="text-and-file"><textarea v-model="kubeSignReq.CSR" style="height:7lh;"></textarea>
       <input type="file" accept=".csr" @change="loadCSR" /></span>
    </p>
    <p>User: <input type="text" v-model="kubeSignReq.User"/></p>
    <p>Group: <input type="text" v-model="kubeSignReq.Group"/>
       ← <a href="#" @click.prevent="kubeSignReq.Group=''">clear</a>, <a href="#" @click.prevent="kubeSignReq.Group='system:masters'">system:masters</a>
    </p>
    <p><button :disabled="loading" @click="kubeCASign">{{ loading ? 'signing...' : 'Sign Kubernetes API access' }}</button></p>
  </div>

  <div v-if="accessType == 'download-set'">
    <h4>Grant download access</h4>
    <p>Generates a signed download set granting access to the selected assets for all {{ hostCount }} hosts in this cluster.</p>
    <h4>Available assets</h4>
    <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="loading || selectedAssetList.length==0" @click="generateDownloadSet">{{ loading ? 'generating...' : 'Generate download set' }}</button></p>
    <div v-if="downloadSet" class="term">
      <a :href="'/public/download-set?set='+downloadSet" target="_blank">/public/download-set?set={{ downloadSet }}</a>
      <br/>
      <button @click="copyDownloadSetUrl">Copy URL</button>
    </div>
  </div>
`
}
