/* global Bdf */

Bdf.FileInput = {};

Bdf.FileInput.bindFileEvents = function ($element, settings) {
    var classes = {
        input: $element.attr("class"),
        dragover: "global-FileInput_dragover",
        filled: "global-FileInput_filled",
        filled_many: "global-FileInput_filled_many"
    };
    var callbacks = {
        change: false
    }
    if (settings) {
        if (settings.classes) {
            for(let prop in settings.classes) {
                classes[prop] = settings.classes[prop];
            }
        }
        if (settings.callbacks) {
            for(let prop in settings.callbacks) {
                callbacks[prop] = settings.callbacks[prop];
            }
        }
    }
    _bind($element);
    
    function _bind($el) {
        $el.on("dragover", function (event) {
            this.classList.add(classes.dragover);
            event.preventDefault();
        });
        $el.on("dragleave", function () {
            _removeDragOverClass(this);
        });
        $el.on("drop", function () {
            _removeDragOverClass(this);
        });
        $el.on("change", _change);
    };
    
    function _change() {
        let changedFileInput = this;
        _removeDragOverClass(changedFileInput);
        changedFileInput.classList.add(classes.filled);
        if (changedFileInput.files.length > 1) {
            let array = new Array();
            for(let file of changedFileInput.files) {
                array.push({
                    name: file.name
                });
            }
            let html = Bdf.render("bdf:filelist", {
                inputId: changedFileInput.id,
                files: array
            });
            let $currentList = $$(changedFileInput.id, "filelist");
            if ($currentList.length > 0) {
                $currentList.replaceWith(html);
            } else {
                $(changedFileInput).after(html);
            }
            changedFileInput.classList.add(classes.filled_many);
        } else {
            $$(changedFileInput.id, "filelist").replaceWith("");
            changedFileInput.classList.remove(classes.filled_many);
        }
        let $parent = $(this).parent();
        let isFull = true;
        let $fileInputList = $parent.find("input");
        for(let i = 0; i < $fileInputList.length; i++) {
            let fileInput = $fileInputList[i];
            if (fileInput.files.length === 0) {
                isFull = false;
            }
        }
        if (isFull) {
            let newGenId = Bdf.generateId();
            $parent.append(Bdf.render("bdf:fileinput", {
                name: changedFileInput.name,
                genId: newGenId,
                classes: classes.input
            }));
            _bind($$(newGenId));
        }
        if (callbacks.change) {
            callbacks.change();
        }
    }
    
    function _removeDragOverClass(input) {
        input.classList.remove(classes.dragover);
    }
};
