var Editor = {
    init: function () {
        this._editUrl = z.bom.getURLSearchParam(window.location.href, "url");
        this.initView();
        this.initController();
    },
    initView: function () {
        this.codeEditor = monaco.editor.create(z.dom.query("#editorDiv"), {
            language: 'html',
            theme: 'vs',
            automaticLayout: true,
            folding: true, foldingStrategy: 'indentation',
            overviewRulerBorder: false,
            scrollBeyondLastLine: false,
            scrollbar: {verticalScrollbarSize: 7, horizontalScrollbarSize: 7},
            minimap: {enabled: false},
            autoClosingBrackets: 'always', autoClosingDelete: 'always', autoClosingQuotes: 'always',
            contextmenu: false
        });
        this.loadEditPage();
    },
    loadEditPage: function () {
        var src = "Page Not Found"
        if (!this._editUrl) {
            this.codeEditor.setValue(src);
            return;
        }
        var link = z.dom.query("#aLink");
        link.innerHTML = this._editUrl;
        link.setAttribute("href", this._editUrl);
        this.loadPageSource(null, this._editUrl, function (result, success) {
            if (success !== false) {
                src = result.substring(0, result.indexOf("</html>") + 7);
            }
            this.codeEditor.setValue(src);
            this.updateIFrame();
        }, this);
    },
    loadPageSource: function (key, url, callBack, context) {
        if (key) {
            var cached = z.bom.getLocalStorage(key);
            if (cached) {
                callBack.apply(context, [cached]);
                return;
            }
        }
        z.ajax.get(url, {
            complete: function (status, result) {
                if (status === 200) {
                    if (key) {
                        z.bom.setLocalStorage(key, result, 12 * 60);
                    }
                } else {
                    if (status === 408) {
                        result = "load '" + url + "' timeout";
                    } else {
                        result = "load '" + url + "' fail";
                    }
                }
                callBack.apply(context, [result, status === 200])
            }
        });
    },
    initController: function () {
        z.dom.event.onclick("#runBtn", this.updateIFrame, this);
    },
    updateIFrame: function () {
        var editValue = this.codeEditor.getValue();
        editValue = editValue.replace('<!--<link rel="stylesheet" href="../../_lib/focus-ui/theme/bootstrap.min.css">-->',
            '<link rel="stylesheet" href="../../_lib/focus-ui/theme/bootstrap.min.css">'); //widgets theme
        editValue = editValue.replace('<!--<link rel="stylesheet" href="../_lib/focus-ui/theme/bootstrap.min.css">-->',
            '<link rel="stylesheet" href="../_lib/focus-ui/theme/bootstrap.min.css">'); //widgets theme
        var editUrlPrefix = this._getResourceUrlPrefix();
        if (editUrlPrefix) {
            editValue = editValue.replace(/(href|src)(.*)(=)('|")?(.*)(.css|.js)/g, '$1$2$3$4' + editUrlPrefix + '$5$6') //css+js
            editValue = editValue.replace(/(image)('|")?(:).*('|")(.*)(\/_icons)/g, '$1$2$3$4' + editUrlPrefix + '$5$6')//image
        }
        console.log(editValue);
        z.dom.empty("#ifDiv");
        z.widget.loading(null, "#ifDiv")
        var iframe = z.dom.create("iframe");
        iframe.setAttribute("sandbox", "allow-pointer-lock allow-scripts allow-downloads allow-same-origin allow-popups allow-popups-to-escape-sandbox allow-modals");
        iframe.setAttribute("srcdoc", editValue);
        z.dom.query("#ifDiv").appendChild(iframe);

        z.util.callLater(function () {
            z.widget.loading(false, "#ifDiv")
        }, 30);
    },
    _getResourceUrlPrefix: function () {
        var urlDemoIndex = this._editUrl.indexOf("/demo/");
        if (urlDemoIndex < 0) {
            return ""
        }
        var urlPrefix = this._editUrl.substr(urlDemoIndex + 6)
        urlPrefix = urlPrefix.substr(0, urlPrefix.lastIndexOf("/"));
        return "../" + urlPrefix + "/";
    }
};
z.ready(function () {
    var monaco_load_times = 0;
    var init_func = function () {
        if (!window.monaco || !monaco.editor) { //for loader
            monaco_load_times++;
            if (monaco_load_times < 2000) {//60s
                z.util.callLater(init_func, 30);
            }
            return;
        }
        Editor.init();
    };
    init_func();
});