/* global Bdf,$$,Illustration,Overlay */

Illustration.Change = {};

Illustration.Change.ReplaceFunction = null;

Illustration.Change.ARGS = {
    clientId: "",
    changeType: "",
    appelant: "",
    tmpFileName: "",
    album: "",
    illustrationId: null,
    imagePath: "",
    originalFileName: ""
};

Illustration.Change.init = function (args) {
    var genId = Bdf.generateId();
    var isCreation = (args.changeType === Illustration.CREATION_CHANGETYPE);
    var resizeRatio = 0;
    var nextArray = [];
    var previousArray = [];
    var tmpFileName = args.tmpFileName;
    var imgAreaSelect = null;
    $$(args.clientId).html(Bdf.render("illustration:client-change", {
        args: args,
        genId: genId
    }));
    _$$("cancel").click(function () {
        window.close();
    });
    _$$("confirm").click(_updateAppelant);
    _$$("crop").click(_cropTool);
    _$$("resize").click(_resizeTool);
    _$$("replace").click(_replaceTool);
    _$$("previous").click(_previousTool);
    _$$("next").click(_nextTool);
    _$$("reset").click(_resetTool);
    _$$("cropform").ajaxForm({
        dataType: 'json',
        data: {
          json: "illustration-tmpfile"  
        },
        success: function (data, textStatus, jqXHR, $form) {
            if (Bdf.checkError(data)) {
                if (data.tmpFile) {
                    _newImage(data.tmpFile.name);
                }
            }
        }
    });
    _$$("resizeform").ajaxForm({
        dataType:  'json',
        data: {
          json: "illustration-tmpfile"  
        },
        beforeSubmit: function (arr, $form, options) {
            return _resizeTest();
        },
        success: function (data, textStatus, jqXHR, $form) {
            if (Bdf.checkError(data)) {
                if (data.tmpFile) {
                    _newImage(data.tmpFile.name);
                }
            }
        }
    });
    _$$("input", "width").on("input", _widthChange);
    _$$("input", "height").on("input", _heightChange);
    imgAreaSelect = _$$("image").imgAreaSelect({
        disable: true,
        instance: true,
        handles: true,
        onSelectChange: function (image, rectangle) {
            _$$("cropsubmit").prop("disabled", false);
            _$$("cropbounds").html(rectangle.x1 + "," + rectangle.y1 + "," + rectangle.width + "," + rectangle.height);
        },
        onSelectEnd: function (image, rectangle) {
            let $form = _$$("cropform");
            $$($form, {_element: "input", _name: "x"}).val(rectangle.x1);
            $$($form, {_element: "input", _name: "y"}).val(rectangle.y1);
            $$($form, {_element: "input", _name: "width"}).val(rectangle.width);
            $$($form, {_element: "input", _name: "height"}).val(rectangle.height);
        }
    });
    
    
    function _$$(id) {
        if (arguments.length > 1) {
            id = Array.from(arguments).join("_");
        }
        return $$(genId, id);
    }
    
    function _updateAppelant() {
        window.opener.Ficheform.AlbumInclude.afterChange(args.changeType, args.appelant, tmpFileName);
        window.close();
    }
    
    function _cropTool() {
        _disableCurrentTool();
        _$$("crop").addClass("illustration-CurrentAction");
        imgAreaSelect.setOptions({enable: true});
        _$$("panel", "cropinfos").addClass("illustration-CurrentInfos");
    }
    
    function _previousTool() {
        if (previousArray.length === 0) {
            return;
        }
        _disableCurrentTool();
        let previousTmpFileName = previousArray.pop();
        nextArray.push(tmpFileName);
        _renameTmpFile(previousTmpFileName);
        _updateStates();
    }
    
    function _nextTool() {
        if (nextArray.length === 0) {
            return;
        }
        _disableCurrentTool();
        let nextTmpFileName = nextArray.pop();
        previousArray.push(tmpFileName);
        _renameTmpFile(nextTmpFileName);
        _updateStates();
    }
    
    function _replaceTool() {
        _disableCurrentTool();
        _$$("replace").addClass("illustration-CurrentAction");
        let appelant = Bdf.generateId();
        let overlayId = Illustration.Change.showReplaceImage(args.album, appelant);
        Bdf.putAppelantCallback(appelant, function (newTmpFileName) {
            Overlay.end(overlayId, function () {
                if (newTmpFileName) {
                    _newImage(newTmpFileName);
                }
            });
        });
    }
    
    function _resetTool() {
        if (tmpFileName === "_ORIGINAL") {
            return;
        }
        _newImage("_ORIGINAL");
    }
    
    function _resizeTool() {
        _disableCurrentTool();
        _$$("resize").addClass("illustration-CurrentAction");
        let $illustrationImage = _$$("image");
        let width = $illustrationImage.width();
        let height = $illustrationImage.height();
        resizeRatio = width / height;
        _$$("panel", "resizeinfos").addClass("illustration-CurrentInfos");
        _$$("input", "width").val(width).focus();
        _$$("input", "height").val(height);
    }
    
    function _widthChange() {
        if (!_resizeTest()) {
            return;
        }
        _$$("resizesubmit").prop("disabled", false);
        let width = _$$("input", "width").val();
        _$$("input", "height").val(Math.round(width / resizeRatio));
    }

    function _heightChange() {
        if (!_resizeTest()) {
            return;
        }
        _$$("resizesubmit").prop("disabled", false);
        let height = _$$("input", "height").val();
        _$$("input", "width").val(Math.round(height * resizeRatio));
    }
    
    function _resizeTest() {
        let $widthInput = _$$("input", "width");
        let $heightInput = _$$("input", "height");
        let ok = true;
        let width = $widthInput.val();
        let height = $heightInput.val();
        if (Illustration.is_int(width)) {
            $widthInput.removeClass("illustration-NotInteger");
        } else {
            $widthInput.addClass("illustration-NotInteger");
            ok = false;
        }
        if (Illustration.is_int(height)) {
            $heightInput.removeClass("illustration-NotInteger");
        } else {
            $heightInput.addClass("illustration-NotInteger");
            ok = false;
        }
        return ok;
    }
    
    function _newImage(newTmpFileName) {
        _disableCurrentTool();
        previousArray.push(tmpFileName);
        nextArray = [];
        _renameTmpFile(newTmpFileName);
        _updateStates();
    }
    
    function _disableCurrentTool() {
        $(".illustration-CurrentAction").removeClass("illustration-CurrentAction");
        $(".illustration-CurrentInfos").removeClass("illustration-CurrentInfos");
        _$$("cropsubmit").prop("disabled", true);
        _$$("resizesubmit").prop("disabled", true);
        _$$("cropbounds").html("");
        imgAreaSelect.cancelSelection();
        imgAreaSelect.setOptions({disable: true});
    }
    
    function _renameTmpFile(newTmpFileName) {
        tmpFileName = newTmpFileName;
        $$({_element: "input", _name: "tmpfile"}).val(newTmpFileName);
        let $illustrationImage = _$$("image");
        imgAreaSelect.cancelSelection();
        if (newTmpFileName === "_ORIGINAL") {
            $illustrationImage.attr("src", "illustrations/" + args.originalFileName);
        } else {
            $illustrationImage.attr("src", "output/tmp/" + newTmpFileName);
        }
    }
    
    function _updateStates() {
        let nextLength = nextArray.length;
        _$$("next").prop("disabled", (nextLength === 0));
        let previousLength = previousArray.length;
        _$$("previous").prop("disabled", (previousLength === 0));
        if (!isCreation) {
            _$$("confirm").prop("disabled", (previousLength === 0));
        }
        _$$("reset").prop("disabled", (tmpFileName === "_ORIGINAL"));
    }
    
};

Illustration.Change.showReplaceImage = function (album, appelant) {
    var overlayId = Overlay.start({
        header: Bdf.Loc.escape("_ title.album.replaceupload"),
        content: Bdf.render("illustration:overlay/replaceimage", {
            album: album,
            appelant: appelant
        }),
        footer: "",
        supplementaryClasses: {
            dialog: "illustration-Overlay"
        }
    });
    return overlayId;
};

$(function () {
    Bdf.initTemplates();
    Illustration.Change.init(Illustration.Change.ARGS);
});
