/* global Bdf,$$ */

var FilesUpload = {};

FilesUpload.ARGS = {
    step: "",
    callKey: ""
};

FilesUpload.initForm = function(args) {
    var $fileInput = $$({_element: "input", _type: "file"});
    $$({_element: "button", _type: "submit"}).prop("disabled", true);
    Bdf.FileInput.bindFileEvents($fileInput, {
        callbacks: {
            change: function () {
                $$({_element: "button", _type: "submit"}).prop("disabled", false);
                var resizeFunction = window.parent.Bdf.getRegistredFunction("resize/" + args.callKey);
                resizeFunction($(".filesupload-Page").height() + 30);
            }
        }
    });
};

FilesUpload.initResult = function (args) {
    var clientId = args.clientId;
    var result = args.result;
    var callKey = args.callKey;
    $$(clientId).html(Bdf.render("filesupload:client-result", {
        clientId : clientId
    }));
    $$(clientId, "confirm").click(function () {
        if (result.type === "multi") {
            let index = 0;
            for(let group of result.groupArray) {
                _checkNameChange(index, group);
                index++;
            }
        }
        let callback = window.parent.Bdf.getCallback(args.callKey);
        if (callback) {
            callback(result);
        }
    });
    
    if (result.type === "unique") {
        $$(clientId, "body").html(Bdf.render("filesupload:result-unique", {
            tmpFileArray : result.tmpFileArray,
            uploadErrorArray: result.uploadErrorArray
        }));
    } else if (result.type === "multi") {
        let callOptions = window.parent.Bdf.getRegistredObject("options/" + callKey);
        let namingInstruction = "";
        if (callOptions) {
            namingInstruction = callOptions.namingInstruction;
        }
        $$(clientId, "body").html(Bdf.render("filesupload:result-multi", {
            groupArray : result.groupArray,
            uploadErrorArray: result.uploadErrorArray,
            namingInstruction: namingInstruction
        }));
    }
    
    function _checkNameChange(index, group) {
        let input = $$(clientId, {_element: "input", _name: "group-" + index})[0];
        Bdf.log(input);
        if (input.checkValidity()) {
            group.normalizedBasename = input.value;
        }
    }
};

Bdf.addTemplateOptions({
    helpers: {
        tmpPath: function (tmpFile) {
            return Bdf.toTmpPath(tmpFile);
        }
    }
});

$(function () {
    Bdf.initTemplates();
    if (FilesUpload.ARGS.step === "form") {
        FilesUpload.initForm(FilesUpload.ARGS);
    } else if (FilesUpload.ARGS.step === "result") {
        FilesUpload.initResult(FilesUpload.ARGS);
    }
    
});