<template>

    <div id="download">
        <pay v-if="!error && !showDl" :objectId="dlId"  :invoice="invoice"></pay>
        <div v-if="error" class="f4 mv5 light-red ttu">{{errorMsg}}</div>
        <upload v-if="error"></upload>
        <a v-if="showDl" :href="dlLink" download="download.zip">download file</a>

    </div>

</template>

<script>
import { mapState, mapGetters } from 'vuex'
import Pay from './Pay.vue';
import Api from './api.js';
import Upload from './Upload.vue';


export default {
    name: 'DownloadView',
    props: ['dlId'],
    data(){
        return {
            dlLink: "if",
            showDl: false,
            error: false,
            errorMsg: "",
        }
    },
    created(){
        let self = this
        // Query for download invoice
        Api.download(this.dlId)

        .then((res)=>{

            if (res.status === 404){
                self.error = true
                self.errorMsg = "this link does not exist anymore"

                // ask payment
            } else if ( res.status === 402) {
                return res.json()
                    .then((data)=>{
                        this.$store.commit('setInvoice', data.invoice)
                        this.$store.commit('setFiles', data.files)

                    Api.pollInvoice(data.invoice.rhash)
                    .then((res)=>{
                        // invoice paid we can try again to download
                        if(res.ok){
                            self.fetchDownloadKey()
                        }
                    })
                    }) .catch((e)=>{console.log(e)})

            } else {
                    console.log("calling set download")
                    res.json().then((data)=>{
                        console.log(data)
                        self.setDownload(data.download_key)
                    })

            }
        })
    },
    methods: {
        fetchDownloadKey() {
            Api.download(this.dlId)
                .then((res)=>{
                if (!res.ok ) {
                    this.error = true
                    this.errMsg = "an error occured, try reloading the page"
                } else {
                    res.json().then((data)=>{
                        this.setDownload(data.download_key)
                    })
                }


            })
        },
        setDownload(downloadKey){
            this.showDl = true;
            this.dlLink = Api.endPoints.getFiles + '/' + downloadKey
        }
    },

    computed: {
        ...mapState({
            invoice: state => state.base.invoice,
            files: state => state.down.files,
        }),
        ...mapGetters([
            'paid',
            'unpaid'
        ]),
        downloadLink(){
            return 'TODO'
        },
    },
    components: {
        Pay,
        Upload,
    }
}

</script>
