<template>
    <section class="item-manager">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3" v-cloak>
            <div class="col-span-1">
                <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>
            <div class="col-span-1 lg:col-span-2">
                <div v-if="items && items.length" class="item-list">
                    <div v-if="state === 'loading'" class="h-14">
                        <Spinner/>
                    </div>
                    <div v-else :class="['has-items', state]">
                        <draggable :list="items" @update="updateSortOrder">
                            <transition-group name="list" tag="div">
                                <gallery-builder-item
                                    v-for="(item, index) in items"
                                    :key="item.id"
                                    :index="index"
                                    :item="item"
                                    :current-item="currentItem"
                                    :imageUrl="imageUrl"
                                    @editItem="editItem"
                                    @deleteItem="deleteItem"
                                >
                                </gallery-builder-item>
                            </transition-group>
                        </draggable>
                    </div>
                </div>
                <div v-else :class="['no-items', state]">
                    <v-card>
                        <div class="message text-center">
                            <div class="message-text font-semibold">
                                {{ message }}
                            </div>
                        </div>
                    </v-card>
                </div>
            </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 Modal from "../Modal";
import Spinner from "../Spinner";
import GalleryBuilderItem from "./GalleryBuilderItem";
import Draggable from 'vuedraggable';

export default {
    components : {
        GalleryBuilderItem,
        Modal,
        Spinner,
        Draggable
    },

    props : {
        gallery : {
            type : Object,
            required : true,
        },
        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 items found';
                    }
                })
                .catch(e => {
                    this.state = 'error';
                    this.message = e.message;
                });
        },
        updateSortOrder() {
            this.items.map((item, index) => {
                item.sort_order = index + 1;
                window.axios.post(this.updateUrl, item);
            });
        },

        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 item
                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>
