// Не редактировать!
var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
var {Services} = Cu.import("resource://gre/modules/Services.jsm", {});
var PREF_BRANCH = "extensions.user_chrome_files.";
var Branch, Prefs;
var user_chrome = {
    options: {
        t_enable: true,
        b_enable: true,
        v_enable: true,
        t_collapsed: false,
        b_collapsed: false,
        v_collapsed: false,
        v_bar_start: true,
        v_autohide: false,
        v_fullscreen: true,
        v_showdelay: 300,
        v_hidedelay: 2000
    },
    initialized: false,
    vertical_top_bottom_bar_enable: true,
    custom_agent_style: false,
    custom_user_style: false,
    custom_author_style: false,
    custom_scripts: false,
    get styleSS() {
        delete this.styleSS;
        return this.styleSS = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
    },
    get styleURI() {
        delete this.styleURI;
        return this.styleURI = Services.io.newURI("chrome://user_chrome_files/content/vertical_top_bottom_bar/vertical_top_bottom_bar.css", null, null);
    },
    get _loadIntoWindow() {
        delete this._loadIntoWindow;
        this.init();
        return this._loadIntoWindow = function(win) {
            var loader = Services.scriptloader;
            try {
                var utils = ("windowUtils" in win && win.windowUtils instanceof Ci.nsIDOMWindowUtils) ? win.windowUtils : win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
                utils.loadSheet(this.styleURI, utils.USER_SHEET);
            } catch(e) {
                Cu.reportError(e);
            }
            if (this.vertical_top_bottom_bar_enable) {
                try {
                    loader.loadSubScript("chrome://user_chrome_files/content/vertical_top_bottom_bar/vertical_top_bottom_bar.js", win, "UTF-8");
                    var options = this.options;
                    if (options.t_enable)
                        options.t_collapsed = Prefs.getBoolPref("top_collapsed");
                    if (options.b_enable)
                        options.b_collapsed = Prefs.getBoolPref("bottom_collapsed");
                    if (options.v_enable)
                        options.v_collapsed = Prefs.getBoolPref("vertical_collapsed");
                    win.vertical_top_bottom_bar.options = options;
                    win.vertical_top_bottom_bar.constructor();
                } catch(e) {
                    Cu.reportError(e);
                }
            }
            if (this.custom_scripts) {
                try {
                    loader.loadSubScript("chrome://user_chrome_files/content/custom_scripts/custom_script_win.js", win, "UTF-8");
                } catch(e) {
                    Cu.reportError(e);
                }
            }
        };
    },
    loadIntoWindow: function(win, href) {
        if (href.startsWith("chrome://browser/content/browser.x"))
            this._loadIntoWindow(win);
    },
    loadPrefsStyle: function() {
        try {
            Branch = Services.prefs.getDefaultBranch(PREF_BRANCH);
            Prefs = Services.prefs.getBranch(PREF_BRANCH);
            Branch.setBoolPref("vertical_top_bottom_bar_enable", true);
            Branch.setBoolPref("vertical_enable", true);
            Branch.setBoolPref("top_enable", true);
            Branch.setBoolPref("bottom_enable", true);
            Branch.setBoolPref("vertical_collapsed", false);
            Branch.setBoolPref("vertical_bar_start", true);
            Branch.setBoolPref("vertical_autohide", false);
            Branch.setBoolPref("vertical_fullscreen", true);
            Branch.setIntPref("vertical_showdelay", 300);
            Branch.setIntPref("vertical_hidedelay", 2000);
            Branch.setBoolPref("top_collapsed", false);
            Branch.setBoolPref("bottom_collapsed", false);
            Branch.setBoolPref("custom_agent_style", false);
            Branch.setBoolPref("custom_user_style", false);
            Branch.setBoolPref("custom_author_style", false);
            Branch.setBoolPref("custom_scripts", false);
            this.vertical_top_bottom_bar_enable = Prefs.getBoolPref("vertical_top_bottom_bar_enable");
            this.custom_agent_style = Prefs.getBoolPref("custom_agent_style");
            this.custom_user_style = Prefs.getBoolPref("custom_user_style");
            this.custom_author_style = Prefs.getBoolPref("custom_author_style");
            this.custom_scripts = Prefs.getBoolPref("custom_scripts");
        } catch(e) {
            Cu.reportError(e);
        }
        if (this.custom_agent_style) {
            try {
                var agentURI = Services.io.newURI("chrome://user_chrome_files/content/agent_style.css", null, null);
                if (!this.styleSS.sheetRegistered(agentURI, this.styleSS.AGENT_SHEET))
                    this.styleSS.loadAndRegisterSheet(agentURI, this.styleSS.AGENT_SHEET);
            } catch(e) {
                Cu.reportError(e);
            }
        }
        if (this.custom_user_style) {
            try {
                var userURI = Services.io.newURI("chrome://user_chrome_files/content/user_style.css", null, null);
                if (!this.styleSS.sheetRegistered(userURI, this.styleSS.USER_SHEET))
                    this.styleSS.loadAndRegisterSheet(userURI, this.styleSS.USER_SHEET);
            } catch(e) {
                Cu.reportError(e);
            }
        }
        if (this.custom_author_style) {
            try {
                var authorURI = Services.io.newURI("chrome://user_chrome_files/content/author_style.css", null, null);
                if (!this.styleSS.sheetRegistered(authorURI, this.styleSS.AUTHOR_SHEET))
                    this.styleSS.loadAndRegisterSheet(authorURI, this.styleSS.AUTHOR_SHEET);
            } catch(e) {
                Cu.reportError(e);
            }
        }
    },
    _aboutPrefs: function() {
        var contractID = "@mozilla.org/network/protocol/about;1?what=user-chrome-files";
        var classID = Components.ID(Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID().toString());
        var { nsIAboutModule } = Ci;
        function aboutUserChromePrefs() {}
        aboutUserChromePrefs.prototype = {
            classDescription: "about:user-chrome-files",
            classID: classID,
            contractID: contractID,
            QueryInterface: function(aIID) {
                if (aIID.equals(nsIAboutModule) || aIID.equals(Ci.nsISupports)) {
                    return this;
                }
                throw Cr.NS_NOINTERFACE;
            },
            newChannel: function(uri, loadInfo) {
                var chan = Services.io.newChannelFromURIWithLoadInfo(Services.io.newURI("chrome://user_chrome_files/content/options/prefs.xhtml"), loadInfo);
                chan.owner = Services.scriptSecurityManager.getSystemPrincipal();
                return chan;
            },
            getURIFlags: function(uri) {
                return nsIAboutModule.ALLOW_SCRIPT;
            }
        };
        var newFactory = {
            createInstance: function(outer, iid) {
                if (outer) {
                    throw Components.results.NS_ERROR_NO_AGGREGATION;
                }
                return (new aboutUserChromePrefs()).QueryInterface(iid);
            }
        };
        var registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
        registrar.registerFactory(classID, "aboutUserChromePrefs", contractID, newFactory);
    },
    get aboutPrefs() {
        delete this.aboutPrefs;
        try {
            this._aboutPrefs();
        } catch(e) {
            return this.aboutPrefs = false;
        }
        return this.aboutPrefs = true;
    },
    restartMozilla: function(nocache = false) {
        var cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool);
        Services.obs.notifyObservers(cancelQuit, "quit-application-requested", "restart");
        if (cancelQuit.data)
            return false;
        if (nocache)
            Services.appinfo.invalidateCachesOnRestart();
        var restart = Services.startup;
        restart.quit(restart.eAttemptQuit | restart.eRestart);
    },
    init: function() {
        if (this.initialized) return;
        this.initialized = true;
        var CustomizableUI;
        try {
            CustomizableUI = Cu.import("resource:///modules/CustomizableUI.jsm", {}).CustomizableUI;
        } catch(e) {
            return;
        }
        var ns_xul = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
        try {
            var aboutPrefs = this.aboutPrefs;
            CustomizableUI.createWidget({
                id: "add-open-about-config-button",
                type: "custom",
                label: "Открыть настройки",
                tooltiptext: "ЛКМ: Открыть настройки в окне\nСКМ: Открыть about:config\nПКМ: Открыть настройки во вкладке",
                onBuild: function (document) {
                    var win = document.defaultView;
                    var prefsInfo = "chrome://user_chrome_files/content/options/prefs.xhtml";
                    if (aboutPrefs)
                        prefsInfo = "about:user-chrome-files";
                    if ("gInitialPages" in win && win.gInitialPages.indexOf(prefsInfo) == -1)
                        win.gInitialPages.push(prefsInfo);
                    var toolbarbutton_0 = document.createElementNS(ns_xul, "toolbarbutton");
                    toolbarbutton_0.id = "add-open-about-config-button";
                    toolbarbutton_0.setAttribute("label", "Открыть настройки");
                    toolbarbutton_0.setAttribute("context", false);
                    toolbarbutton_0.setAttribute("tooltiptext", "ЛКМ: Открыть настройки в окне\nСКМ: Открыть about:config\nПКМ: Открыть настройки во вкладке");
                    toolbarbutton_0.addEventListener("click", function(event) {
                        if (event.button == 0) {
                            var prefwin = Services.wm.getMostRecentWindow("user_chrome_prefs:window");
                            if (prefwin)
                                prefwin.focus();
                            else
                                win.openDialog("chrome://user_chrome_files/content/options/prefs_win.xhtml", "user_chrome_prefs:window", "centerscreen,resizable,dialog=no");
                        } else if (event.button == 1) {
                            win.switchToTabHavingURI("about:config", true, {
                                relatedToCurrent: true,
                                triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()
                            });
                        } else if (event.button == 2) {
                            win.switchToTabHavingURI(prefsInfo, true, {
                                relatedToCurrent: true,
                                triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()
                            });
                        }
                    }, false);
                    toolbarbutton_0.classList.add("toolbarbutton-1");
                    toolbarbutton_0.classList.add("chromeclass-toolbar-additional");
                    return toolbarbutton_0;
                }
            });
        } catch(e) {}
        if (this.vertical_top_bottom_bar_enable) {
            var options = this.options;
            var v_enable, t_enable, b_enable;
            try {
                v_enable = options.v_enable = Prefs.getBoolPref("vertical_enable");
                t_enable = options.t_enable = Prefs.getBoolPref("top_enable");
                b_enable = options.b_enable = Prefs.getBoolPref("bottom_enable");
                if (v_enable) {
                    options.v_collapsed = Prefs.getBoolPref("vertical_collapsed");
                    options.v_bar_start = Prefs.getBoolPref("vertical_bar_start");
                    options.v_autohide = Prefs.getBoolPref("vertical_autohide");
                    options.v_fullscreen = Prefs.getBoolPref("vertical_fullscreen");
                    options.v_showdelay = Prefs.getIntPref("vertical_showdelay");
                    options.v_hidedelay = Prefs.getIntPref("vertical_hidedelay");
                }
                if (t_enable)
                    options.t_collapsed = Prefs.getBoolPref("top_collapsed");
                if (b_enable)
                    options.b_collapsed = Prefs.getBoolPref("bottom_collapsed");
            } catch(e) { }
            try {
                if (v_enable) {
                    CustomizableUI.registerArea("add-additional-vertical-bar", {
                        type: CustomizableUI.TYPE_TOOLBAR,
                        defaultPlacements: ["add-view-bookmarks-sidebar-button", "add-view-history-sidebar-button", "add-additional-vertical-spring", "add-open-about-config-button"],
                        defaultCollapsed: false
                    });
                }
            } catch(e) {}
            try {
                if (t_enable) {
                    CustomizableUI.registerArea("add-additional-top-bar", {
                        type: CustomizableUI.TYPE_TOOLBAR,
                        defaultPlacements: ["add-open-directories-button", "add-additional-top-spring", "add-restart-app"],
                        defaultCollapsed: false
                    });
                }
            } catch(e) {}
            try {
                if (b_enable) {
                    CustomizableUI.registerArea("add-additional-bottom-bar", {
                        type: CustomizableUI.TYPE_TOOLBAR,
                        defaultPlacements: ["add-additional-bottom-closebutton", "add-additional-bottom-spring"],
                        defaultCollapsed: false
                    });
                }
            } catch(e) {}
            try {
                if (t_enable) {
                    CustomizableUI.createWidget({
                        id: "add-additional-top-spring",
                        type: "custom",
                        label: "Растягивающийся интервал",
                        onBuild: function(document) {
                            var toolbaritem = document.createElementNS(ns_xul, "toolbaritem");
                            toolbaritem.id = "add-additional-top-spring";
                            toolbaritem.className = "add-additional-springs";
                            toolbaritem.setAttribute("label", "Растягивающийся интервал");
                            toolbaritem.setAttribute("type", "custom");
                            toolbaritem.setAttribute("flex", "1");
                            return toolbaritem;
                        }
                    });
                }
            } catch(e) {}
            try {
                if (v_enable) {
                    CustomizableUI.createWidget({
                        id: "add-additional-vertical-spring",
                        type: "custom",
                        label: "Растягивающийся интервал",
                        onBuild: function(document) {
                            var toolbaritem = document.createElementNS(ns_xul, "toolbaritem");
                            toolbaritem.id = "add-additional-vertical-spring";
                            toolbaritem.className = "add-additional-springs";
                            toolbaritem.setAttribute("label", "Растягивающийся интервал");
                            toolbaritem.setAttribute("type", "custom");
                            toolbaritem.setAttribute("flex", "1");
                            return toolbaritem;
                        }
                    });
                }
            } catch(e) {}
            try {
                if (b_enable) {
                    CustomizableUI.createWidget({
                        id: "add-additional-bottom-spring",
                        type: "custom",
                        label: "Растягивающийся интервал",
                        onBuild: function(document) {
                            var toolbaritem = document.createElementNS(ns_xul, "toolbaritem");
                            toolbaritem.id = "add-additional-bottom-spring";
                            toolbaritem.className = "add-additional-springs";
                            toolbaritem.setAttribute("label", "Растягивающийся интервал");
                            toolbaritem.setAttribute("type", "custom");
                            toolbaritem.setAttribute("flex", "1");
                            return toolbaritem;
                        }
                    });
                }
            } catch(e) {}
            try {
                CustomizableUI.createWidget({
                    id: "add-restart-app",
                    type: "custom",
                    label: "Перезагрузка",
                    tooltiptext: "ЛКМ: Перезапустить приложение\nСКМ: Перезапустить без дополнений\nПКМ: Отключить загрузку содержимого из кеша и перезапустить",
                    onBuild: function(document) {
                        var win = document.defaultView;
                        var toolbarbutton_0 = document.createElementNS(ns_xul, "toolbarbutton");
                        toolbarbutton_0.id = "add-restart-app";
                        toolbarbutton_0.setAttribute("label", "Перезагрузка");
                        toolbarbutton_0.setAttribute("context", false);
                        toolbarbutton_0.setAttribute("tooltiptext", "ЛКМ: Перезапустить приложение\nСКМ: Перезапустить без дополнений\nПКМ: Отключить загрузку содержимого из кеша и перезапустить");
                        toolbarbutton_0.addEventListener("click", function(event) {
                            if (event.button == 0)
                                user_chrome.restartMozilla();
                            else if (event.button == 1)
                                win.safeModeRestart();
                            else if (event.button == 2) {
                                event.preventDefault();
                                event.stopPropagation();
                                user_chrome.restartMozilla(true);
                            }
                        }, false);
                        toolbarbutton_0.classList.add("toolbarbutton-1");
                        toolbarbutton_0.classList.add("chromeclass-toolbar-additional");
                        return toolbarbutton_0;
                    }
                });
            } catch(e) {}
            try {
                if (v_enable) {
                    CustomizableUI.createWidget({
                        id: "add-additional-vertical-toggle-button",
                        label: "Переключить Верт. панель",
                        tooltiptext: "Скрыть / Показать Вертикальную панель",
                        onCommand: function(event) {
                            CustomizableUI.setToolbarVisibility("add-additional-vertical-bar", event.target.ownerDocument.querySelector("#add-additional-vertical-bar").collapsed);
                        }
                    });
                }
            } catch(e) {}
            try {
                if (t_enable) {
                    CustomizableUI.createWidget({
                        id: "add-additional-top-toggle-button",
                        label: "Переключить Доп. панель",
                        tooltiptext: "Скрыть / Показать Дополнительную панель",
                        onCommand: function(event) {
                            CustomizableUI.setToolbarVisibility("add-additional-top-bar", event.target.ownerDocument.querySelector("#add-additional-top-bar").collapsed);
                        }
                    });
                }
            } catch(e) {}
            try {
                if (b_enable) {
                    CustomizableUI.createWidget({
                        id: "add-additional-bottom-toggle-button",
                        label: "Переключить Ниж. панель",
                        tooltiptext: "Скрыть / Показать Нижнюю панель",
                        onCommand: function(event) {
                            CustomizableUI.setToolbarVisibility("add-additional-bottom-bar", event.target.ownerDocument.querySelector("#add-additional-bottom-bar").collapsed);
                        }
                    });
                }
            } catch(e) {}
            try {
                CustomizableUI.createWidget({
                    id: "add-view-history-sidebar-button",
                    label: "История",
                    tooltiptext: "Показать / Скрыть Историю",
                    onCommand: function(event) {
                        var win = event.target.ownerDocument.defaultView;
                        if ("SidebarUI" in win)
                            win.SidebarUI.toggle("viewHistorySidebar");
                        else if ("toggleSidebar" in win)
                            win.toggleSidebar("viewHistorySidebar");
                    }
                });
            } catch(e) {}
            try {
                CustomizableUI.createWidget({
                    id: "add-view-bookmarks-sidebar-button",
                    label: "Закладки",
                    tooltiptext: "Показать / Скрыть Закладки",
                    onCommand: function(event) {
                        var win = event.target.ownerDocument.defaultView;
                        if ("SidebarUI" in win)
                            win.SidebarUI.toggle("viewBookmarksSidebar");
                        else if ("toggleSidebar" in win)
                            win.toggleSidebar("viewBookmarksSidebar");
                    }
                });
            } catch(e) {}
            try {
                CustomizableUI.createWidget({
                    id: "add-open-directories-button",
                    type: "custom",
                    label: "Открыть папку",
                    tooltiptext: "ЛКМ: Папка user_chrome_files\nСКМ: Папка профиля\nПКМ: Папка установки",
                    onBuild: function (document) {
                        var toolbarbutton_0 = document.createElementNS(ns_xul, "toolbarbutton");
                        toolbarbutton_0.id = "add-open-directories-button";
                        toolbarbutton_0.setAttribute("label", "Открыть папку");
                        toolbarbutton_0.setAttribute("context", false);
                        toolbarbutton_0.setAttribute("tooltiptext", "ЛКМ: Папка user_chrome_files\nСКМ: Папка профиля\nПКМ: Папка установки");
                        toolbarbutton_0.addEventListener("click", function(event) {
                            var dirs;
                            if (event.button == 0) {
                                dirs = Services.dirsvc.get("UChrm", Ci.nsIFile);
                                dirs.append("user_chrome_files");
                                if (dirs.exists()) dirs.launch();
                            } else if (event.button == 1) {
                                dirs = Services.dirsvc.get("ProfD", Ci.nsIFile);
                                if (dirs.exists()) dirs.launch();
                            } else if (event.button == 2) {
                                dirs = Services.dirsvc.get("GreD", Ci.nsIFile);
                                if (dirs.exists()) dirs.launch();
                            }
                        }, false);
                        toolbarbutton_0.classList.add("toolbarbutton-1");
                        toolbarbutton_0.classList.add("chromeclass-toolbar-additional");
                        return toolbarbutton_0;
                    }
                });
            } catch(e) {}
        }
        if (this.custom_scripts) {
            try {
                var scope = Cu.Sandbox(Services.scriptSecurityManager.getSystemPrincipal(), {
                    wantComponents: true,
                    sandboxName: "user_chrome_files: custom_scripts"
                });
                scope.Services = Services;
                scope.CustomizableUI = CustomizableUI;
                Services.scriptloader.loadSubScript("chrome://user_chrome_files/content/custom_scripts/custom_script.js", scope, "UTF-8");
            } catch(e) {
                Cu.reportError(e);
            }
        }
    }
};
user_chrome.loadPrefsStyle();
