

class TextRichEditor {

    getTool() {
        let tools = ["H1", "H2", "H3", "Paragraph", "Bold", "Italic", "Underline", "Stroke", "List",
            "FontSize", "FontColor", "BackgroundColor", "Link",
            "AlignLeft", "AlignCenter", "AlignRight", "ShowBlock" , "TableTool"
        ];

        return tools;
    }

    constructor(control, options) {

        this.sourceControl = control;

        //On est deja en édition 
        if (this.sourceControl.className == "txtEditor") {
            return;
        }

        this.sourceControlType = control.tagName;
        this.sourceControl.style.display = "none";

        this.tools = this.getTool();
        if (options != undefined) {
            if (options.tools != undefined) {
                for (let optionTool in options.tools) {

                    this.tools.push(options.tools[optionTool]);
                }
            }

            if (options.events != undefined) {

                this.events = options.events;
            }
        }
        this.init();
    }

    init() {
        this.createEditor();

        if (this.sourceControlType == "DIV") {
            this.inputArea.innerHTML = this.sourceControl.innerHTML;
        } else {
            this.inputArea.innerHTML = this.sourceControl.value;
        }
        this.initEvent();
    }

    initEvent() {
        let instance = this;
        this.inputArea.addEventListener("keyup", (e) => {
            instance.inputAreaChanged(e, instance);
        });

            instance.initEvent
        instance.initEventImg();
    }

    initEventImg() {
        let instance = this;
        let images = this.inputArea.querySelectorAll("img");

        for (let i = 0; i < images.length; i++) {
            images[i].removeEventListener("click", function (e) {
                instance.editImageProperty(e, instance)
            });
            images[i].addEventListener("click", function (e) {
                instance.editImageProperty(e, instance)
            });
        }
    }

    editImageProperty(e, instance) {
        let imgSource = e.srcElement;

        let view = "<div style='text-align : center'>";
        view += "<form id='imagePropertyForm'>"
        view += "<label class='width100'>" + Language.GetCode("Base.Width") + "</label>";
        view += "<input class='form-control' style='width:75%;display:inline-block;' name='width' type='number' value='" + imgSource.style.width.replace("px", "") + "'>";
        view += "<select  class='form-control' id='widthType' style='width:25%;display:inline-block;'><option value='px'>px<option value='%'>%</option></select>";
      

        view += "<label>" + Language.GetCode("Base.Position") + "</label>";
        view += "<select class='form-control' id='position' name='position'><option value='left'>left</option><option value='center'>center</option><option value='right'>right</option></select>"

        view += "<button class='btn btn-primary' style='margin-top:5px' id='btnApplyPropertyImage'>" + Language.GetCode("Base.Apply") + "</button>";
        view += "</form></div>";

        instance.dialog(view, function () {
            Event.AddById("btnApplyPropertyImage", "click", (e) => {

                e.preventDefault();
                let width = Form.GetValue("imagePropertyForm", "width");
                let widthType = Form.GetValue("imagePropertyForm", "widthType");
                
                imgSource.style.width = width + widthType;

                let position = Form.GetValue("imagePropertyForm", "position");
                imgSource.parentNode.style.textAlign = position;

                TextRichEditor.removeDialog();
            });
        });
    }

    dialog(view, initHandler) {

        let TextRidhEditorDialog = document.getElementById("TextRidhEditorDialog");

        if (TextRidhEditorDialog == null) {

            let instance = this;

            let dialog = document.createElement("div");
            dialog.id = "TextRidhEditorDialog";
            dialog.style.width = "350px";
            dialog.style.height = "100vh";
            dialog.style.position = "fixed";
            dialog.style.padding = "10px";
            dialog.style.top = "0";
            dialog.style.right = "0";
           // dialog.style.border = "1px solid grey";
            //dialog.style.borderRadius = "8px";
            dialog.style.boxShadow = "10px 10px 20px rgba(0, 0, 0, 0.4)";
            dialog.style.zIndex = "9999999999";
            dialog.style.background = "white";
            dialog.innerHTML = "<div class='tool' style='float:right'><i id='btnCloseDialog' class='fa fa-times'></i></tool>";
            dialog.innerHTML += view;

            document.body.appendChild(dialog);

            Event.AddById("btnCloseDialog", "click", function () {
                TextRichEditor.removeDialog();
            });

            if (initHandler) {
                initHandler();
            }
        }

    }

    static removeDialog(e) {

        let instance = this;

        if (e == undefined || (e.srcElement.tagName != "IMG" && e.srcElement.parentNode.parentNode.parentNode.id != "TextRidhEditorDialog")) {
            document.removeEventListener("click", TextRichEditor.removeDialog);
            let TextRidhEditorDialog = document.getElementById("TextRidhEditorDialog");
            TextRidhEditorDialog.parentNode.removeChild(TextRidhEditorDialog);
        }
    }

    inputAreaChanged() {
        if (this.sourceControlType == "DIV") {
            this.sourceControl.innerHTML = this.inputArea.innerHTML;
        } else {
            this.sourceControl.value = this.inputArea.innerHTML;
        }
    }

    createEditor() {

        this.editor = document.createElement("div");
        this.editor.className = "txtEditor";

        this.createToolBar();
        this.createInputArea();
        this.sourceControl.parentNode.prepend(this.editor);
    }

    createToolBar() {
        this.toolBar = document.createElement("div");
        this.toolBar.className = 'toolBar';
        this.appendTools();

        this.editor.append(this.toolBar);
    }

    createInputArea() {
        this.inputArea = document.createElement("div");
        this.inputArea.className = "inputArea";
        this.inputArea.setAttribute("contenteditable", "true");
        this.editor.append(this.inputArea);
    }

    appendTools() {

        this.toolsObject = Array();

        for (let tool in this.tools) {

            let Tool = eval('new ' + this.tools[tool] + '(this)');

            for (let event in this.events) {
                if (this.events[event]["tool"] == this.tools[tool]) {
                    Tool.setEvent(this.events[event]["events"])
                }
            }
            this.toolBar.append(Tool.getIconeContainer());


            this.toolsObject.push(Tool);
        }
    }

    getContent() {
        this.clearBeforeSave();
        let content  = this.inputArea.innerHTML;
        return content;    
    }

    getJSONContent(){
        let content = this.getContent();
        return JSON.stringify({content:content});
    }

    getCleanContent(){
         let content = this.getContent();
         content = content.replace(/&gt;/g, '>');
         content = content.replace(/&lt;/g, '<');
      
        return content;
    }

    setSelectedNode(node) {
        this.node = node;
    }

    appendImage(imgSrc, width) {

        let selection = window.getSelection();
        let image = document.createElement("img")
        image.src = imgSrc;
        image.style.width = width + "px";

        this.node.append(image);
    }

    appendLink(label, link) {

        let selection = window.getSelection();
        let a = document.createElement("a")
        a.innerHTML = label;
        a.href = link;

        this.node.append(a);
    }

    appendTable(column, row){
        let selection = window.getSelection();
        let container = document.createElement("div");
    
        let html = "<table>";

        for(let i = 0; i < row; i++){
            html += "<tr>";

            for(let j = 0; j < column; j++){
                html += "<td></td>";
            }
            html += "<tr>";

        }

        html += "<table>";
    
        container.innerHTML = html;
    
        this.node.append(container);
    } 


    clearBeforeSave() {

        for (let tools in this.toolsObject) {
            if (this.toolsObject[tools].name == "ShowBlock") {

                if (this.toolsObject[tools].activated) {
                    this.toolsObject[tools].execute();
                }
            }
        }
    }

    quit() {
        this.inputAreaChanged();
        this.editor.parentNode.removeChild(this.editor);
        this.sourceControl.style.display = "";
    }
};



