/* global Bdf,Ficheform,$$ */

Ficheform.AlbumInclude =  {};

Ficheform.AlbumInclude.TmpFile = {};

Ficheform.AlbumInclude.Illustration = {};

Ficheform.AlbumInclude.CREATION_CHANGETYPE = "creation";
Ficheform.AlbumInclude.ILLUSTRATION_CHANGETYPE = "illustration";
Ficheform.AlbumInclude.TMPFILE_CHANGETYPE = "tmpfile";

Ficheform.AlbumInclude.init = function () {
    Bdf.FileInput.bindFileEvents($$({ficheformRole: "illustration-file"}).find("input"));
    $$({ficheformEntry: "album-include"}).each(function (index, entry) {
        let entryKey = entry.dataset.ficheformKey;
        let albumName = entry.dataset.subsetName;
        Ficheform.AlbumInclude.checkHidden(entry);
        $$(entry, {ficheformRole: "illustration"}).each(function (index2, illustrationDiv) {
            let illustrationDivId = illustrationDiv.id;
            let $illustrationDiv = $(illustrationDiv);
            $illustrationDiv.prepend(Bdf.render("ficheform:album/illustration", {
                illustrationDivId: illustrationDivId,
                noTab: Ficheform.getOption("noTab")
            }));
            _initIllustrationInfo(albumName, $illustrationDiv, illustrationDiv);
            $$(illustrationDivId, "change").click(function () {
                Ficheform.AlbumInclude.Illustration.openChange(entryKey, illustrationDivId);
            });
            $$(illustrationDivId, "remove").click(function () {
                Ficheform.AlbumInclude.Illustration.remove(entryKey, illustrationDivId);
            });
        });
        let createButtonId = Bdf.generateId();
        $$(entry, {ficheformRole: "illustration-input"}).append(Bdf.render("ficheform:album/create", {
            buttonId: createButtonId,
            noTab: Ficheform.getOption("noTab")
        }));
        $$(createButtonId).click(function () {
            _openCreate(entryKey, albumName);
        });
    });

    
    function _initIllustrationInfo(albumName, $illustrationDiv, illustrationDiv) {
        let illustrationInfo = {
            subsetName: albumName,
            originalSrc: Ficheform.AlbumInclude.getImgJqueryElement($illustrationDiv).attr("src"),
            tmpFileName: null,
            itemId: illustrationDiv.dataset.subsetItemId
        };
        $illustrationDiv.data("illustrationInfo",  illustrationInfo);
    }

    function _openCreate(entryKey, albumName) {
        let url = "album?page=illustration-upload-new&album=" + albumName + "&callkey=" + entryKey;
        Ficheform.openDialog(url, "pioche_"+ entryKey, 620, 510);
    }
};

Ficheform.AlbumInclude.checkHidden = function (entry) {
    var length = $$(entry, {ficheformRole: "illustration-list"}).children().length;
    Ficheform.checkEnumerationCell(entry, length);
};

Ficheform.AlbumInclude.testFileInputChange = function () {
    var $parent = $(this).parent();
    var isFull = true;
    var $fileInputList = $parent.find("input");
    for(var i = 0; i < $fileInputList.length; i++) {
        var fileInput = $fileInputList[i];
        if (fileInput.files.length === 0) {
            isFull = false;
        }
    }
    if (isFull) {
        var texte = '<input type="file" class="ficheform-Full global-FileInput TEMPORARY" name="' + this.name + '" size="70" multiple accept="png,jpg,jpeg,bmp,gif">';
        $parent.append(texte);
    }
    $parent.find("input.TEMPORARY").change(Ficheform.AlbumInclude.testFileInputChange).removeClass("TEMPORARY");
};

Ficheform.AlbumInclude.addDragAndDrop = function ($elements) {
    
};

Ficheform.AlbumInclude.afterChange = function (changeType, callKey, tmpFileName) {
    if (changeType === Ficheform.AlbumInclude.CREATION_CHANGETYPE) {
        let entryKey = callKey;
        Ficheform.AlbumInclude.createIllustration(entryKey, tmpFileName);
    } else if (changeType === Ficheform.AlbumInclude.TMPFILE_CHANGETYPE) {
        let idx = callKey.indexOf("/");
        let entryKey = callKey.substring(0, idx);
        let illustrationDivId = callKey.substring(idx+1);
        Ficheform.AlbumInclude.TmpFile.afterChange(entryKey, illustrationDivId, tmpFileName);
    } else if (changeType === Ficheform.AlbumInclude.ILLUSTRATION_CHANGETYPE) {
        let idx = callKey.indexOf("/");
        let entryKey = callKey.substring(0, idx);
        let illustrationDivId = callKey.substring(idx+1);
        Ficheform.AlbumInclude.Illustration.afterChange(entryKey, illustrationDivId, tmpFileName);
    }
    Ficheform.signalChange();
};

Ficheform.AlbumInclude.createIllustration = function (entryKey, tmpFileName) {
    var entry = Ficheform.entry(entryKey);
    var $field = $$(entry, {ficheformRole: "createfield"});
    $field.val($field.val() + tmpFileName + ";");
    var illustrationDivId = Bdf.generateId();
    Ficheform.AlbumInclude.TmpFile.putTmpFileName(illustrationDivId, tmpFileName);
    $$(entry, {ficheformRole: "illustration-list"}).append(Bdf.render("ficheform:album/new", {
        illustrationDivId: illustrationDivId,
        tmpFileName: tmpFileName,
        noTab: Ficheform.getOption("noTab")
    }));
    Ficheform.AlbumInclude.checkHidden(entry);
    $$(illustrationDivId, "change").click(function () {
        Ficheform.AlbumInclude.TmpFile.openChange(entryKey, illustrationDivId);
    });
    $$(illustrationDivId, "remove").click(function () {
        Ficheform.AlbumInclude.TmpFile.remove(entryKey, illustrationDivId);
    });
    Ficheform.signalChange();
};


/** Illustration ***************************************************************************/

Ficheform.AlbumInclude.Illustration.openChange = function (entryKey, illustrationDivId) {
    var $illustrationDiv = $$(illustrationDivId);
    var callKey = entryKey + "/" + illustrationDivId;
    var illustrationInfo = $illustrationDiv.data("illustrationInfo");
    var url = "album?page=illustration-change&changetype=" + Ficheform.AlbumInclude.ILLUSTRATION_CHANGETYPE + "&album=" + illustrationInfo.subsetName + "&callkey=" + callKey + "&id=" + illustrationInfo.itemId;
    if (illustrationInfo.tmpFileName) {
        url = url + "&tmpfile=" + illustrationInfo.tmpFileName;
    }
    Ficheform.openDialog(url,"pioche_"+ entryKey, 620, 510);
};

Ficheform.AlbumInclude.Illustration.afterChange = function (entryKey, illustrationDivId, newTmpFileName) {
    var entry = Ficheform.entry(entryKey);
    var $illustrationDiv = $$(illustrationDivId);
    var illustrationInfo = $illustrationDiv.data("illustrationInfo");
    var $img = Ficheform.AlbumInclude.getImgJqueryElement($illustrationDiv);
    var $uri = $$($illustrationDiv, {ficheformRole: "illustration-uri"});
    if (newTmpFileName === "_ORIGINAL") {
        $img.attr("src", illustrationInfo.originalSrc);
        illustrationInfo.tmpFileName = null;
        $uri.removeClass("ficheform-illustration-Changed");
        _deleteUpdate(illustrationInfo.itemId);
    } else {
        $img.attr("src", "output/tmp/mini-" + newTmpFileName);
        illustrationInfo.tmpFileName = newTmpFileName;
        $uri.addClass("ficheform-illustration-Changed");
        _putUpdate(illustrationInfo.itemId, newTmpFileName);
    }
    Ficheform.signalChange();
    
    
    function _deleteUpdate(illustrationItemId) {
        let $field = $$(entry, {ficheformRole: "updatefield"});
        let currentVal = $field.val();
        if ((!currentVal) || (currentVal.length === 0)) {
            return;
        }
        $field.val(Ficheform.removeFromValue(currentVal, illustrationItemId, "="));
        Ficheform.signalChange();
    }
    
    function _putUpdate(illustrationItemId, newTmpFileName) {
        let $field = $$(entry, {ficheformRole: "updatefield"});
        var newToken = illustrationItemId + "=" + newTmpFileName;
        var currentVal = $field.val();
        if ((!currentVal) || (currentVal.length === 0)) {
            $field.val(newToken);
            return;
        }
        var array = currentVal.split(";");
        var length = array.length;
        var done = false;
        for(let i = 0; i < length; i++) {
            let token = array[i];
            let idx = token.indexOf("=");
            if (idx < 1) {
                continue;
            }
            if (token.substring(0,idx) == illustrationItemId) {
                array[i] = newToken;
                done = true;
                break;
            }
        }
        if (!done) {
            array.push(newToken);
        }
        $field.val(array.join(";"));
        Ficheform.signalChange();
    }
};

Ficheform.AlbumInclude.Illustration.remove = function (entryKey, illustrationDivId) {
    var ok = confirm(Bdf.Loc.get("_ warning.album.remove_illustration"));
    if (ok) {
        let entry = Ficheform.entry(entryKey);
        let $illustrationDiv = $$(illustrationDivId);
        let illustrationInfo = $illustrationDiv.data("illustrationInfo");
        let $field = $$(entry, {ficheformRole: "removefield"});
        $field.val($field.val() + illustrationInfo.itemId + ";");
        $illustrationDiv.remove();
        Ficheform.AlbumInclude.checkHidden(entry);
        Ficheform.signalChange();
    }
};



/** TmpFile ***************************************************************************/

Ficheform.AlbumInclude.TmpFile.tmpFileNameMap = new Object();

Ficheform.AlbumInclude.TmpFile.openChange = function (entryKey, illustrationDivId) {
    var entry = Ficheform.entry(entryKey);
    var albumName = entry.dataset.subsetName;
    var tmpFileName = Ficheform.AlbumInclude.TmpFile.getTmpFileName(illustrationDivId);
    var callKey = entryKey + "/" + illustrationDivId;
    var url = "album?page=illustration-change&changetype=" + Ficheform.AlbumInclude.TMPFILE_CHANGETYPE + "&album=" + albumName + "&callkey=" + callKey + "&tmpfile=" + tmpFileName;
    Ficheform.openDialog(url,"pioche_"+ entryKey, 620, 510);
};

Ficheform.AlbumInclude.TmpFile.afterChange = function (entryKey, illustrationDivId, newTmpFileName) {
    var entry = Ficheform.entry(entryKey);
    var $illustrationDiv = $$(illustrationDivId);
    var oldTmpFileName = Ficheform.AlbumInclude.TmpFile.getTmpFileName(illustrationDivId);
    var $field = $$(entry, {ficheformRole: "createfield"});
    var currentText = $field.val();
    var idx = currentText.indexOf(oldTmpFileName);
    if (idx > -1) {
        currentText = currentText.substring(0, idx) + currentText.substring(idx + newTmpFileName.length + 1);
    }
    currentText = currentText + newTmpFileName + ";";
    $field.val(currentText);
    Ficheform.AlbumInclude.getImgJqueryElement($illustrationDiv).attr("src", "output/tmp/mini-" + newTmpFileName);
    Ficheform.AlbumInclude.TmpFile.putTmpFileName(illustrationDivId, newTmpFileName);
    Ficheform.signalChange();
};

Ficheform.AlbumInclude.TmpFile.remove = function (entryKey, illustrationDivId) {
    var ok = confirm(Bdf.Loc.get("_ warning.album.remove_tmpfile"));
    if (ok) {
        var entry = Ficheform.entry(entryKey);
        var tmpFileName = Ficheform.AlbumInclude.TmpFile.getTmpFileName(illustrationDivId);
        var $field = $$(entry, {ficheformRole: "createfield"});
        var currentText = $field.val();
        var idx = currentText.indexOf(tmpFileName);
        if (idx > -1) {
            currentText = currentText.substring(0, idx) + currentText.substring(idx + tmpFileName.length + 1);
            $field.val(currentText);
        }
        $$(illustrationDivId).remove();
        Ficheform.AlbumInclude.checkHidden(entry);
        Ficheform.signalChange();
    }
};

Ficheform.AlbumInclude.TmpFile.getTmpFileName = function (illustrationDivId) {
    return Ficheform.AlbumInclude.TmpFile.tmpFileNameMap[illustrationDivId];
};

Ficheform.AlbumInclude.TmpFile.putTmpFileName = function (illustrationDivId, tmpFileName) {
    Ficheform.AlbumInclude.TmpFile.tmpFileNameMap[illustrationDivId] = tmpFileName;
};


/** Utils ***************************************************************************/

Ficheform.AlbumInclude.getImgJqueryElement = function ($illustration) {
    return $$($illustration, {ficheformRole: "illustration-image"});
};