/* global Bdf,$$,Overlay,Ficheform,CodeMirror,Infinity */

Ficheform.Section.Overlay = {};

Ficheform.Section.Overlay.end = function ($form, codeMirror) {
    if (!codeMirror.hasFocus()) {
        codeMirror.focus();
    }
    Overlay.end($form);
};

Ficheform.Section.Overlay.showFootnoteForm = function (codeMirror) {
    var genId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ label.edition.footnote"),
        content: Bdf.render("ficheform:section/overlay/footnoteform", {
            genId: genId,
            number: _getNumber()
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ link.global.ok'
            }}),
        formAttrs: {
            action: "#"
        },
        formSubmit: function ($form) {
            let ref = $$(genId, "reference").val();
            let text = $$(genId, "text").val();
            let cursor = codeMirror.getCursor();
            codeMirror.replaceRange("[>(" + ref + ")]", cursor);
            let doc = codeMirror.getDoc();
            doc.replaceRange("\n[#(" + ref + ")] " + text, {line: doc.lineCount(), ch: 0});
            codeMirror.focus();
            Ficheform.Section.Overlay.end($form, codeMirror);
            return false;
        },
        afterStart: function () {
            $$(genId, "text").focus();
        }
    });
    
    function _getNumber() {
        let number = 0;
        let matches = codeMirror.getDoc().getValue().matchAll(/\[>\(([0-9]+)/g);
        for(let match of matches) {
            let current = parseInt(match[1]);
            number = Math.max(current, number);
        }
        number++;
        return number;
    }
};

Ficheform.Section.Overlay.showUrlForm = function (codeMirror) {
    var urlrefId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ label.edition.urlref"),
        content: Bdf.render("ficheform:section/overlay/urlform", {
            urlrefId: urlrefId
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ link.global.ok'
            }}),
        formAttrs: {
            action: "#"
        },
        formSubmit: function ($form) {
            let ref = $$(urlrefId).val();
            Bdf.Ficheblock.wrapSelection(codeMirror, "[a(" + Bdf.escape(ref) +") ", "]");
            Ficheform.Section.Overlay.end($form, codeMirror);
            return false;
        },
        afterStart: function () {
            $$(urlrefId).focus();
        }
    });   
};

Ficheform.Section.Overlay.showFicheForm = function (codeMirror) {
    var ficherefId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ label.edition.ficheref"),
        content: Bdf.render("ficheform:section/overlay/ficheform", {
            ficherefId: ficherefId
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ link.global.ok'
            }}),
        formAttrs: {
            action: "#"
        },
        formSubmit: function ($form) {
            var ref = $$(ficherefId).val();
            Bdf.Ficheblock.wrapSelection(codeMirror, "[f(" + Bdf.escape(ref) +") ", "]");
            Ficheform.Section.Overlay.end($form, codeMirror);
            return false;
        },
        afterStart: function () {
            $$(ficherefId).focus();
            $$(ficherefId, "pioche").click(function () {
                let url = "pioche?page=fiche&subsets=&appelant=" + ficherefId + "&limit=1";
                Ficheform.openDialog(url,"pioche_overlay_ficheref", 430,510);
            });
        }
    });
};

Ficheform.Section.Overlay.showPasteAndConvert = function (codeMirror) {
    var id = Bdf.generateId();
    var conversionCodeMirror;
    var onPaste = false;
    Overlay.start({
        header: Bdf.Loc.escape("_ label.edition.tool_paste"),
        content: Bdf.render("ficheform:section/overlay/pasteandconvert", {
            id: id
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ link.edition.insert'
            }}),
        formAttrs: {
            action: "#"
        },
        formSubmit: function ($form) {
            let cursor = codeMirror.getCursor();
            codeMirror.replaceRange(conversionCodeMirror.getValue(), cursor, cursor, "+overlay");
            Ficheform.Section.Overlay.end($form, codeMirror);
            return false;
        },
        afterStart: function () {
            let target = $$.one(id, "target");
            _focusOnTarget(target);
            $(target).on("paste", function (event) {
               onPaste = true;
            }).on("input", function (event) {
                if (onPaste) {
                    _updateCodemirror();
                }
               onPaste = false;
            });
            conversionCodeMirror = Bdf.toCodeMirror($$.one(id, "ficheblock"), {
                mode: 'ficheblock',
                theme: 'bdf',
                lineWrapping: true
            });
        }
    });
    
    
    function _focusOnTarget(target) {
        let s = window.getSelection();
        let r = document.createRange();
        target.innerHTML = '\u00a0';
        r.selectNodeContents(target);
        s.removeAllRanges();
        s.addRange(r);
        document.execCommand('delete', false, null);
    }
    
    function _updateCodemirror() {
        $.ajax ({
            url: Bdf.URL + "importation",
            method: "post",
            data: {
                source:  $$(id, "target").html(),
                cmd: "HtmlConversion",
                json: "ficheblocksyntax"
            },
            dataType: "json",
            success: function (data, textStatus) {
                conversionCodeMirror.setValue(data.ficheblockSyntax);
            }
        });
    }
    
};

Ficheform.Section.Overlay.showStyleForm = function (codeMirror) {
    var genId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ label.edition.tool_stylechoice"),
        content: Bdf.render("ficheform:section/overlay/styleform", {
            genId: genId
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ link.global.ok'
            }}),
        formAttrs: {
            action: "#"
        },
        formSubmit: function ($form) {
            let checkedRadio = $$.first($form, {_element: "input", _name: "type", _checked: true});
            if (checkedRadio) {
                let start = "[" + checkedRadio.value;
                let subfieldsContent = "";
                let ref = $$(checkedRadio.id, "_ref").val();
                if (ref) {
                    subfieldsContent += Bdf.Ficheblock.escapeValue(ref);
                }
                let subfields = checkedRadio.dataset.subfields;
                if (subfields) {
                    let subfieldsArray = subfields.split(',');
                    for(let i= 0, len= subfieldsArray.length; i < len; i++) {
                        let name = subfieldsArray[i];
                        let value = $$(checkedRadio.id, name).val();
                        if (value) {
                            if (subfieldsContent.length > 0) {
                                subfieldsContent += " ";
                            }
                            subfieldsContent += name;
                            subfieldsContent += '="';
                            subfieldsContent += Bdf.Ficheblock.escapeValue(value);
                            subfieldsContent += '"';
                        }
                    }
                }
                if (subfieldsContent.length > 0) {
                    start += "(";
                    start += subfieldsContent;
                    start += ")";
                }
                start += " ";
                Bdf.Ficheblock.wrapSelection(codeMirror, start, "]");
            }
            Ficheform.Section.Overlay.end($form, codeMirror);
            return false;
        },
        afterStart: function (overlayId) {
            Bdf.Deploy.initOverlay(overlayId);
            _checkDim("column1");
            _checkDim("column2");
        }
    });

    function _checkDim(columnName) {
        let $element = $$(genId, columnName);
        let width = Math.max($element.width() + 20, 250);
        $element.css("width", width + "px");
        let height = $element.height() + 50;
        $element.css("height", height + "px");
        $element.css("overflow", "auto");
    }
    
};

Ficheform.Section.Overlay.showZoneForm = function (codeMirror) {
    var genId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ label.edition.tool_zonechoice"),
        content: Bdf.render("ficheform:section/overlay/zoneform", {
            illustrationArray: Ficheform.Section.getUriLinkedToFicheArray("illustration-uri"),
            documentArray: Ficheform.Section.getUriLinkedToFicheArray("document-uri"),
            genId: genId
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ link.global.ok'
            }}),
        formAttrs: {
            action: "#"
        },
        formSubmit: function ($form) {
            let formElement = $form[0];
            let selectedIndex = formElement.zonetype.selectedIndex;
            if (selectedIndex === -1) {
                Ficheform.Section.Overlay.end($form, codeMirror);
                return false;
            }
            let zonetype = formElement.zonetype.options[selectedIndex].value;
            let start = "\n" + Bdf.Ficheblock.getStartSequence(zonetype);

            if (zonetype === "table") {
                if (formElement.tableheader_row.checked) {
                    start += "h";
                }
                if (formElement.tableheader_column.checked) {
                    start += "v";
                }
            } else if (zonetype === "code") {
                var modeSelectedIndex = formElement.indentmode.selectedIndex;
                if (modeSelectedIndex > 0) {
                    start += formElement.indentmode.options[modeSelectedIndex].value;
                }
            } else if (zonetype === "insert_image") {
                var typeSelectedIndex = formElement.imagetype.selectedIndex;
                if (typeSelectedIndex > -1) {
                    start += formElement.imagetype.options[typeSelectedIndex].value;
                }
            } else if (zonetype === "insert_audio") {
                start += "a";
            }
            start += _toLine(formElement.zonenumber, "n");
            start += _toLine(formElement.zonecaption, "l");
            start += _toLine(formElement.illustration, "i");
            start += _toLine(formElement.document, "d");
            start += _toLine(formElement.src, "s");
            start += _toLine(formElement.width, "w");
            start += _toLine(formElement.height, "h");
            start += _toLine(formElement.credit, "c");
            start += _toLine(formElement.url, "r");
            start += _toLine(formElement.alt, "a");
            start += "\n";
            if (zonetype.indexOf("insert_") !== 0) {
                start += "\n";
            }
            var end = Bdf.Ficheblock.getEndSequence(zonetype) + "\n\n";
            var cursor = codeMirror.getCursor();
            var endCursor = {
                ch: 0,
                line: cursor.line + 1
            };
            codeMirror.replaceRange(end, endCursor, endCursor, "+overlay");
            codeMirror.replaceRange(start, cursor, cursor, "+overlay");
            Ficheform.Section.Overlay.end($form, codeMirror);
            return false;
        },
        afterStart: function (overlayId) {
            Bdf.Deploy.initOverlay(overlayId);
            $$(genId, "zonetypeselect").change(function () {
               let selectedIndex = this.selectedIndex;
               if (selectedIndex !== -1) {
                    let zonetype = this.options[selectedIndex].value;
                    $$({_element: "tr", zonetypes: true}).addClass("hidden");
                    $$({_element: "tr", "zonetypes~": zonetype}).removeClass("hidden");
                    if (zonetype === "insert_image") {
                        _changeOrigin($$.one(genId, "imageoriginselect"), "insert_image_");
                    } else if (zonetype === "insert_audio") {
                        _changeOrigin($$.one(genId, "audiooriginselect"), "insert_audio_");
                    }
               }
            });
            $$(genId, "imageoriginselect").change(function () {
               _changeOrigin(this, "insert_image_");
            });
            $$(genId, "audiooriginselect").change(function () {
               _changeOrigin(this, "insert_audio_");
            });
        }
    });


    function _toLine(input, char) {
        if ((input) && (input.value)) {
            return "\n" + char + "=" + input.value;
        }
        return "";
    }
    
    function _changeOrigin(selectElement, type) {
        let selectedIndex = selectElement.selectedIndex;
        for(let i = 0, len = selectElement.options.length; i < len; i++) {
            let originType = type + selectElement.options[i].value;
            if (i === selectedIndex) {
                $$({_element: "tr", "zonetypes~": originType}).removeClass("hidden");
            } else {
                $$({_element: "tr", "zonetypes~": originType}).addClass("hidden");
            }
        }
    }
};

Ficheform.Section.Overlay.showSectionPreview = function (codeMirror, corpus, closeCallback) {
    var frameId = Bdf.generateId();
    var jsonData = null;
    var isLoaded = false;
    var toBeInit = true;
    var overlayCallback = null;
    Overlay.start({
        header: Bdf.Loc.escape("_ title.edition.sectionpreview"),
        content: Bdf.render("ficheform:section/overlay/preview", {
            corpus: corpus,
            frameId: frameId
        }),
        closeKey: "F1",
        supplementaryClasses: {
            dialog: "ficheform-section-PreviewOverlay"
        },
        isWaiting: true,
        afterStart: function (overlayId, waitingCallback) {
            $$.one(frameId).addEventListener("load", function () {
                isLoaded = true;
                _initIframe(overlayId);
            });
            
            let text = codeMirror.getDoc().getValue();
            $.ajax({
                url: Bdf.URL + "edition",
                method: "POST",
                data: {
                    cmd: "SectionParser",
                    corpus: corpus,
                    json: "section",
                    text: text
                },
                dataType: Bdf.jsonDataType,
                success: function (data, textStatus) {
                    jsonData = data;
                    overlayCallback = waitingCallback;
                    _initIframe(overlayId);
                }
            });
        },
        afterEnd: function () {
            closeCallback();
        }
        
    });
    
    function _initIframe(overlayId) {
        if ((jsonData) && (isLoaded) && (toBeInit)) {
            toBeInit = false;
            overlayCallback();
            $$.one(frameId).contentWindow.Preview.update(jsonData.html, codeMirror, overlayId);
        }
    }

};

Ficheform.Section.Overlay.endSectionPreview = function (overlayId, codeMirror, lineNumber) {
    Overlay.end(overlayId, function () {
        let lineIndex = lineNumber-1;
        let start = {
            line: lineIndex,
            ch: 0
        };
        codeMirror.focus();
        codeMirror.setCursor(start);
        codeMirror.setSelection(start, {line: lineIndex, ch: null});
    });
};

