<template>
    <section class="document-manager">

        <div
            class="relative flex justify-center px-6 pt-5 pb-6 mb-6 border-2 border-gray-300 border-dashed rounded-sm text-center hover:bg-gray-200"
        >
            <input v-if="state !== 'uploading'"
                   class="input-file opacity-0 absolute inset-0 cursor-pointer w-full"
                   type="file"
                   multiple
                   @change="onFileChange"
            >

            <div v-if="state === 'uploading'" class="message">
                <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke-linecap="round" stroke-linejoin="round"
                     stroke-width="2" stroke="currentColor"
                     viewBox="0 0 24 24"
                >
                    <path
                        d="M8 17a5 5 0 01-.916-9.916 5.002 5.002 0 019.832 0A5.002 5.002 0 0116 17m-7-5l3-3m0 0l3 3m-3-3v12"
                    ></path>
                </svg>
                <p class="mt-1 text-sm text-indigo-600">
                    Uploading, please wait...
                </p>
                <p class="mt-1 text-xs text-gray-500">
                    This should only take a minute
                </p>
            </div>
            <div v-else-if="state === 'error'" class="message">
                <svg class="mx-auto h-12 w-12 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                     xmlns="http://www.w3.org/2000/svg"
                >
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                </svg>
                <p class="mt-1 text-sm text-red-600">
                    Unfortunately an error occurred...
                </p>
                <p class="mt-1 text-xs text-red-500">
                    {{ message }}
                </p>
            </div>
            <div v-else class="message">
                <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                     xmlns="http://www.w3.org/2000/svg"
                >
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                    />
                </svg>
                <p class="mt-1 text-sm text-gray-600">
                    <span class="text-primary-500">Upload a file</span>
                    or drag and drop
                </p>
                <p class="mt-1 text-xs text-gray-500">
                    PDF, Excel, Power Point, Word up to 10MB
                </p>
            </div>
        </div>

        <div v-if="items && items.length" class="document-list">
            <div v-if="state === 'loading'" class="h-14">
                <Spinner/>
            </div>
            <div v-else :class="['has-items', state]">
                <transition-group name="list" tag="div">
                    <document-manager-item
                        v-for="(item, index) in items"
                        :key="item.id"
                        :index="index"
                        :item="item"
                        :current-item="currentItem"
                        :showUrl="showUrl"
                        :downloadUrl="downloadUrl"
                        @deleteItem="deleteItem"
                    >
                    </document-manager-item>
                </transition-group>
            </div>
        </div>

    </section>
</template>


<script>
import DocumentManagerItem from "./DocumentManagerItem";
import Spinner from "../Spinner";

export default {
    components : {
        DocumentManagerItem,
        Spinner
    },
    props : {
        indexUrl : {
            required : true
        },
        showUrl : {
            required : true
        },
        downloadUrl : {
            required : true
        },
        storeUrl : {
            required : true
        },
        deleteUrl : {
            required : true
        },
    },
    data() {
        return {
            items : [],
            files : [],
            currentItem : {},
            message : '',
            state : 'loading'
        }
    },
    methods : {
        validateIndexUrl() {
            if (!this.indexUrl) {
                this.state = 'error';
                this.message = "Error: Please set the index-url attribute to retrieve existing documents";
            }
        },
        validateStoreUrl() {
            if (!this.indexUrl) {
                this.state = 'error';
                this.message = "Error: Please set the store-url attribute to manage the uploads..";
            }
        },
        validateShowUrl() {
            if (!this.showUrl) {
                this.state = 'error';
                this.message = "Error: Please set the show-url attribute to view uploaded files..";
            }
        },
        validateDownloadUrl() {
            if (!this.showUrl) {
                this.state = 'error';
                this.message = "Error: Please set the download-url attribute to view uploaded files..";
            }
        },
        validateDeleteUrl() {
            if (!this.indexUrl) {
                this.state = 'error';
                this.message = "Error: Please set the delete-url attribute to delete existing documents";
            }
        },
        checkForExistingDocuments() {
            this.state = 'loading';
            this.message = 'Updating, please wait...';
            window.axios
                .get(this.indexUrl)
                .then((response) => {
                    this.items = response.data.items;
                    if (this.items && this.items.length) {
                        this.state = 'success';
                    } else {
                        this.state = 'no-data';
                        this.message = 'No documents found';
                    }
                })
                .catch(e => {
                    this.state = 'error';
                    this.message = e.message;
                });
        },
        onFileChange(e) {

            // Get the files if any
            this.files = e.target.files || e.dataTransfer.files;
            if (!this.files.length) {
                return;
            }

            // Notify the user that we are doing something
            this.state = 'uploading';

            // Loop through all the files in the array
            for (let i = 0; i < this.files.length; i++) {

                // Get the file and make sure the file is an document
                let file = this.files[i];
                // if (!file.name.match('\.pdf')) {
                //     continue;
                // }

                // Upload the file
                this.uploadFile(file);
            }
        },
        uploadFile(file) {

            // Create the form data object for the server
            let formData = new FormData();
            formData.append('file', file);

            // Send the request to the server
            window.axios.post(this.storeUrl, formData)
                .then((response) => {
                    this.state = 'success';
                    this.items.push(response.data.item);
                })
                .catch(e => {
                    this.state = 'error';
                    this.message = e.response.data.message;
                });
        },
        deleteItem(item, index) {
            this.$delete(this.items, index);
            this.state = 'loading';

            window.axios
                .post(this.deleteUrl, {
                    id : item.id,
                })
                .then((response) => {
                    this.state = 'success';
                })
                .catch(e => {
                    this.state = 'error';
                    this.message = e.response.data.message;
                });
        }
    },
    mounted : function () {
        this.validateIndexUrl();
        this.validateStoreUrl();
        this.validateShowUrl();
        this.validateDownloadUrl();
        this.validateDeleteUrl();
        this.checkForExistingDocuments();
    }
}
</script>
