/* global Bdf,Edition,CodeMirror,Infinity,Ficheform,$$ */
/**
 * Objet global définissant l'espace de nom History
  * 
 * @namespace Zoomedit
 */
var Zoomedit = {};

Zoomedit.ARGS = {
    clientId: "",
    callKey: "",
    corpus: ""
};

Zoomedit.init = function (args) {
    var zoomeditId = Bdf.generateId();
    var callerTextArea = _getCallerTextArea(args.callKey); 
    var codeMirrorUnit, sectionTextArea;
    $$(args.clientId).html(Bdf.render("zoomedit:client", {
        zoomeditId: zoomeditId
    }));
    Ficheform.Section.ficheElement = window.opener.document;
    sectionTextArea = _initSectionTextArea();
    codeMirrorUnit = Ficheform.Section.initSectionCodeMirror("body", sectionTextArea, false, Zoomedit.ARGS.corpus);
    $$(zoomeditId, "save").click(_updateCaller);
    $(window).on('unload', _updateCaller);
    Bdf.Shortcut.init();
    
      
    function _initSectionTextArea() {
        let textArea = $$.one(zoomeditId, "section");
        textArea.value = callerTextArea.value;
        callerTextArea.classList.add("ficheform-ZoomedArea");
        let spellchekAttribute = callerTextArea.getAttribute("spellcheck");
        if (spellchekAttribute) {
            textArea.setAttribute("spellcheck", spellchekAttribute);
        }
        if (callerTextArea.lang) {
            textArea.lang = callerTextArea.lang;
            $$.one(zoomeditId, "body").lang = callerTextArea.lang;
        }
        return textArea;
    }
    
    function _updateCaller() {
        codeMirrorUnit.codeMirror.save();
        callerTextArea.value = sectionTextArea.value;
        callerTextArea.classList.remove("ficheform-ZoomedArea");
        window.close();
    }
    
    function _getCallerTextArea(callKey) {
        return window.opener.document.getElementById(callKey);
    }
};


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