<template>
    <section class="image-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">
                    JPG, PNG, GIF up to 10MB
                </p>
            </div>
        </div>

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

        <modal
            :id="'item-modal'"
            :ref="'item-modal'"
            btnPrimaryText="Save Item"
            @btnSecondaryClicked="revertItem"
            @btnPrimaryClicked="updateItem"
        >
            <h3 slot="modal_title" class="text-lg leading-6 font-medium text-gray-900">
                Edit Item
            </h3>

            <div slot="modal_content">
                <div class="form-group">
                    <label class="text-sm leading-5 font-medium text-gray-500">
                        File Name
                    </label>
                    <div class="mt-1 relative rounded-sm shadow-sm">
                        <input
                            class="form-input block w-full rounded-sm sm:text-sm sm:leading-5"
                            type="text"
                            v-model="currentItem.name_formatted"
                        />
                    </div>
                </div>

                <div class="form-group mt-4">
                    <label class="text-sm leading-5 font-medium text-gray-500">
                        Alt Tag
                    </label>
                    <div class="mt-1 relative rounded-sm shadow-sm">
                        <input
                            class="form-input block w-full rounded-sm sm:text-sm sm:leading-5"
                            type="text"
                            v-model="currentItem.title"
                        />
                    </div>
                </div>

            </div>
        </modal>

    </section>
</template>


<script>
import ImageManagerItem from "./ImageManagerItem";
import Modal from "../Modal";
import Spinner from "../Spinner";

export default {
    components : {
        ImageManagerItem,
        Modal,
        Spinner
    },
    props : {
        indexUrl : {
            required : true
        },
        storeUrl : {
            required : true
        },
        updateUrl : {
            required : true
        },
        deleteUrl : {
            required : true
        },
        imageUrl : {
            required : true
        },
    },
    data() {
        return {
            items : [],
            files : [],
            currentItem : {},
            cachedItem : null,
            message : '',
            state : 'loading'
        }
    },
    methods : {
        checkForExistingImages() {
            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 images 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 image
                let file = this.files[i];

                // 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;
                });
        },

        editItem(item, index) {
            this.cachedItem = JSON.parse(JSON.stringify(item));
            this.currentItem = item;
            this.showItemModal();
        },
        revertItem() {
            this.currentItem = this.cachedItem;
            this.cachedItem = null;
            this.hideItemModal();

            // Update the existing item if there is one
            let index = _.findIndex(this.items, {id : this.currentItem.id});
            if (index !== -1) {
                this.items[index] = this.currentItem
            }
        },
        updateItem(item, index) {
            this.hideItemModal();

            window.axios
                .post(this.updateUrl, this.currentItem)
                .then((response) => {
                    // Update the existing item if there is one
                    let index = _.findIndex(this.items, {id : this.currentItem.id});
                    if (index !== -1) {
                        this.currentItem = response.data.item;
                        this.items[index] = this.currentItem;
                    } else {
                        this.currentItem = response.data.item;
                        this.items.push(this.currentItem);
                    }
                })
                .catch(e => {
                    console.log(e.message);
                });
        },
        showItemModal() {
            this.$refs['item-modal'].showModal();
        },
        hideItemModal() {
            this.$refs['item-modal'].closeModal();
        },

        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.checkForExistingImages();
    }
}
</script>
