import Vue from 'vue/dist/vue'
import EventBus from '../util/EventBus';
import EventTypes from '../util/EventTypes';
import MediaClient from "../api/MediaClient";
import {triggerFlashNotification} from "../../flashbag_notification";

Vue.component('library-upload', {
    props: {
        context: {
            type: Object,
            default() {
                return {}
            }
        },
    },
    data: function () {
        return {
            isDragging: false,
            errors: {
                type: Array,
                default() {
                    return []
                }
            },
            successes: {
                type: Array,
                default() {
                    return []
                }
            },
        };
    },
    methods: {
        reset: function () {
            this.errors = [];
            this.successes = [];
        },
        change: function (event) {
            this.reset();
            let files = this.$refs.fileInput.files;
            let validFiles = [];
            [...files].forEach((file) => {
                if (file.size <= this.context.maxUploadSize) {
                    validFiles.push(file);
                } else {
                    this.errors.push('Le fichier "' + file.name + '" dépasse la taille maximale autorisée.')
                }
            });

            if (validFiles.length === 0) {
                // this.errors.push(`Aucun fichier valide parmis la séléction.`);
                return;
            }
            this.$refs.uploadForm.dispatchEvent(new CustomEvent('submit', {cancelable: true}))
        },
        drop: function (event) {
            this.isDragging = false;
            event.preventDefault();
            console.log('media upload drop');
            let fileList = [];
            if (event.dataTransfer.files) {
                [...event.dataTransfer.items].forEach((item, i) => {
                    if (item.kind === "file") {
                        const file = item.getAsFile();
                        fileList.push(file)
                    }
                });
                let dt = new DataTransfer();
                fileList.forEach((f) => dt.items.add(f));
                this.$refs.fileInput.files = dt.files;
                this.$refs.uploadForm.dispatchEvent(new CustomEvent('submit', {cancelable: true}));
            }
        },
        validateUploads: function (files) {
            MediaClient.validateUploads(files)
        },
        clickTransfer: function () {
            console.log('media upload clickTransfer');
            this.$refs.fileInput.click();
        },
        uploadHandler: function (e) {
            e.preventDefault();
            console.log(e);
            let formData = new FormData(this.$refs.uploadForm);
            MediaClient.upload(formData)
                .then((data) => {
                    if (data.successes) {
                        data.successes.forEach((msg) => triggerFlashNotification('success', msg))
                    }
                    if (data.status !== true) {
                        // plain error or partial success, display errors
                        if (data.indexedErrors) {
                            Object.keys(data.indexedErrors)
                                .forEach((file) =>
                                    triggerFlashNotification('error', data.indexedErrors[file] + '(' + file + ')'))
                        }
                    }

                    EventBus.$emit(EventTypes.LIBRARY_UPLOAD_PANE, false);
                    let search = data.files.join(',')
                    EventBus.$emit(EventTypes.LIBRARY_SEARCH, {
                        searchTerm: search
                    });
                });
            return false;
        },
        closeUpload: function (event) {
            event.preventDefault();
            EventBus.$emit(EventTypes.LIBRARY_UPLOAD_PANE, false);
            return false;
        },
    },
    mounted() {
        console.log('upload mounted');
        console.log(this.context);

        this.$refs.dropZone.addEventListener("dragenter", (e) => {
            e.preventDefault();
            return false;
        });
        this.$refs.dropZone.addEventListener("dragover", (e) => {
            this.isDragging = true;
            e.preventDefault();
            return false;
        });
        this.$refs.dropZone.addEventListener("dragleave", (e) => {
            this.isDragging = false;
            e.preventDefault();
            return false;
        });
        this.$refs.dropZone.addEventListener("drop", this.drop);

        this.$refs.uploadForm.addEventListener("submit", this.uploadHandler);
    },
    template: `
      <div class="library-upload">
        <div class="container">
          <div class="row">
            <div class="col">
              <form ref="uploadForm"
                    action=""
                    method="post"
                    enctype="multipart/form-data">
                <div class="row action-bar">
                  <div class="col">
                    <div class="h-stack">
                      <button class="library-upload-btn btn btn-primary"
                              @click="closeUpload"
                      >
                        <i class="fa fa-caret-left"></i> Retour
                      </button>
                      <div class="media-type-select">
                        <label for="media_type_selector">Catégorie</label>
                        <select ref="mediaTypeSelect" name="media_upload_type" id="media_type_selector"
                                class="form-select">
                          <option v-for="mediaType in context.mediaTypesConfig"
                                  :value="mediaType.type">{{ mediaType.label }}
                          </option>
                        </select>
                        <input
                            ref="fileInput"
                            type="file"
                            name="media_upload_file[]"
                            id="media_upload_file"
                            @change="change"
                            style="display: none;"
                            multiple
                        />
                      </div>
                    </div>

                  </div>
                </div>
              </form>

              <div class="info-panel">
                <div class="errors" v-if="errors.length > 0">
                  <div v-for="error in errors">{{ error }}</div>
                </div>
                <div class="successes" v-if="successes.length > 0">
                  <div v-for="success in successes"><i class="fa-solid fa-check"></i> {{ success }}</div>
                </div>
              </div>

              <div
                  ref="dropZone"
                  class="drag-n-drop"
                  :class="{'is-dragging': isDragging}"
                  @click="clickTransfer"
              >
                <i class="fa-solid fa-down-to-bracket"></i>
                <p>Glisser-déposer un fichier pour l'envoyer<br/>(ou cliquer pour parcourir)</p>
              </div>
              <div class="row size-info-pane">
                <div class="col">
                  <p class="max-size">Taille maximale : {{ context.maxUploadSizeReadable }} (<small><i
                      class="fas fa-exclamation-triangle"></i> Lors d'envois multiples, le poids total doit rester
                    inférieur à {{ context.maxUploadSizeReadable }}</small>)</p>
                  <p></p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    `
});