"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.unregisterGlobalShortcuts = exports.registerGlobalShortcuts = exports.toggleSpellChecking = exports.toggleMenuBar = exports.createMenu = void 0;
const auto_launch_1 = __importDefault(require("auto-launch"));
const electron_1 = require("electron");
const path = __importStar(require("path"));
const download_1 = require("../lib/download");
const eventType_1 = require("../lib/eventType");
const zip_1 = require("../lib/zip");
const locale = __importStar(require("../locale"));
const getLogger_1 = require("../logging/getLogger");
const loggerUtils_1 = require("../logging/loggerUtils");
const EnvironmentUtil = __importStar(require("../runtime/EnvironmentUtil"));
const lifecycle = __importStar(require("../runtime/lifecycle"));
const config_1 = require("../settings/config");
const ConfigurationPersistence_1 = require("../settings/ConfigurationPersistence");
const SettingsType_1 = require("../settings/SettingsType");
const WindowManager_1 = require("../window/WindowManager");
const WindowUtil_1 = require("../window/WindowUtil");
const launchCmd = process.env.APPIMAGE || process.execPath;
const logger = (0, getLogger_1.getLogger)(path.basename(__filename));
const launcher = new auto_launch_1.default({
    isHidden: true,
    name: config_1.config.name,
    path: launchCmd,
});
const separatorTemplate = {
    type: 'separator',
};
const createLanguageTemplate = (languageCode) => {
    return {
        click: () => changeLocale(languageCode),
        label: locale.SUPPORTED_LANGUAGES[languageCode],
        type: 'radio',
    };
};
const createLanguageSubmenu = () => {
    return Object.keys(locale.SUPPORTED_LANGUAGES).map(supportedLanguage => createLanguageTemplate(supportedLanguage));
};
const localeTemplate = {
    label: locale.getText('menuLocale'),
    submenu: createLanguageSubmenu(),
};
const aboutTemplate = {
    click: () => electron_1.ipcMain.emit(eventType_1.EVENT_TYPE.ABOUT.SHOW),
    label: locale.getText('menuAbout'),
};
const signOutTemplate = {
    click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.ACTION.SIGN_OUT),
    label: locale.getText('menuSignOut'),
};
const spellingTemplate = {
    checked: ConfigurationPersistence_1.settings.restore(SettingsType_1.SettingsType.ENABLE_SPELL_CHECKING, true),
    click: () => (0, exports.toggleSpellChecking)(),
    label: locale.getText('menuEnableSpellChecking'),
    type: 'checkbox',
};
const conversationTemplate = {
    label: `&${locale.getText('menuConversation')}`,
    submenu: [
        {
            accelerator: 'CmdOrCtrl+N',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.START),
            label: locale.getText('menuStart'),
        },
        separatorTemplate,
        {
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.PING),
            label: locale.getText('menuPing'),
        },
        {
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.CALL),
            label: locale.getText('menuCall'),
        },
        {
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.VIDEO_CALL),
            label: locale.getText('menuVideoCall'),
        },
        separatorTemplate,
        {
            accelerator: 'CmdOrCtrl+I',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.PEOPLE),
            label: locale.getText('menuPeople'),
        },
        {
            accelerator: 'Shift+CmdOrCtrl+K',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.ADD_PEOPLE),
            label: locale.getText('menuAddPeople'),
        },
        separatorTemplate,
        {
            accelerator: 'CmdOrCtrl+D',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.ARCHIVE),
            label: locale.getText('menuArchive'),
        },
        {
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.DELETE),
            label: locale.getText('menuDelete'),
        },
    ],
};
const showWireTemplate = {
    accelerator: 'Alt+CmdOrCtrl+1',
    click: () => { var _a; return (_a = WindowManager_1.WindowManager.getPrimaryWindow()) === null || _a === void 0 ? void 0 : _a.show(); },
    label: `&${config_1.config.name}`,
};
const toggleMenuTemplate = {
    checked: ConfigurationPersistence_1.settings.restore(SettingsType_1.SettingsType.SHOW_MENU_BAR, true),
    click: () => (0, exports.toggleMenuBar)(),
    label: locale.getText('menuShowHide'),
    type: 'checkbox',
};
const toggleFullScreenTemplate = {
    accelerator: EnvironmentUtil.platform.IS_MAC_OS ? 'Alt+Command+F' : 'F11',
    click: () => {
        const mainBrowserWindow = WindowManager_1.WindowManager.getPrimaryWindow();
        if (mainBrowserWindow) {
            mainBrowserWindow.setFullScreen(!mainBrowserWindow.isFullScreen());
        }
    },
    label: locale.getText('menuFullScreen'),
    type: 'checkbox',
};
const toggleAutoLaunchTemplate = {
    checked: ConfigurationPersistence_1.settings.restore(SettingsType_1.SettingsType.AUTO_LAUNCH, false),
    click: () => {
        const shouldAutoLaunch = !ConfigurationPersistence_1.settings.restore(SettingsType_1.SettingsType.AUTO_LAUNCH);
        ConfigurationPersistence_1.settings.save(SettingsType_1.SettingsType.AUTO_LAUNCH, shouldAutoLaunch);
        return shouldAutoLaunch ? launcher.enable() : launcher.disable();
    },
    label: locale.getText('menuStartup'),
    type: 'checkbox',
};
const editTemplate = {
    label: `&${locale.getText('menuEdit')}`,
    submenu: [
        {
            accelerator: 'CmdOrCtrl+Z',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.EDIT.UNDO),
            label: locale.getText('menuUndo'),
        },
        {
            accelerator: 'Shift+CmdOrCtrl+Z',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.EDIT.REDO),
            label: locale.getText('menuRedo'),
        },
        separatorTemplate,
        {
            accelerator: 'CmdOrCtrl+X',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.EDIT.CUT),
            label: locale.getText('menuCut'),
        },
        {
            accelerator: 'CmdOrCtrl+C',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.EDIT.COPY),
            label: locale.getText('menuCopy'),
        },
        {
            accelerator: 'CmdOrCtrl+V',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.EDIT.PASTE),
            label: locale.getText('menuPaste'),
        },
        separatorTemplate,
        {
            accelerator: 'CmdOrCtrl+A',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.EDIT.SELECT_ALL),
            label: locale.getText('menuSelectAll'),
        },
    ],
};
const windowTemplate = {
    label: `&${locale.getText('menuWindow')}`,
    role: 'window',
    submenu: [
        {
            label: locale.getText('menuMinimize'),
            role: 'minimize',
        },
        {
            label: locale.getText('menuClose'),
            role: 'close',
        },
        separatorTemplate,
        {
            accelerator: EnvironmentUtil.platform.IS_MAC_OS ? 'Alt+Cmd+Up' : 'Alt+Shift+Up',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.SHOW_NEXT),
            label: locale.getText('menuNextConversation'),
        },
        {
            accelerator: EnvironmentUtil.platform.IS_MAC_OS ? 'Alt+Cmd+Down' : 'Alt+Shift+Down',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.SHOW_PREVIOUS),
            label: locale.getText('menuPreviousConversation'),
        },
    ],
};
const downloadLogsTemplate = {
    click: () => __awaiter(void 0, void 0, void 0, function* () {
        const logFiles = yield (0, loggerUtils_1.gatherLogs)();
        const archive = yield (0, zip_1.zipFiles)(logFiles);
        const archiveFile = yield (0, zip_1.createFile)(archive);
        yield (0, download_1.downloadLogs)(archiveFile);
    }),
    label: locale.getText('menuDownloadDebugLogs'),
};
const helpTemplate = {
    label: `&${locale.getText('menuHelp')}`,
    role: 'help',
    submenu: [
        {
            click: () => (0, WindowUtil_1.openExternal)(config_1.config.legalUrl, true),
            label: locale.getText('menuLegal'),
        },
        {
            click: () => (0, WindowUtil_1.openExternal)(config_1.config.supportUrl, true),
            label: locale.getText('menuSupport'),
        },
        {
            click: () => (0, WindowUtil_1.openExternal)(EnvironmentUtil.web.getWebsiteUrl(), true),
            label: locale.getText('menuAppURL'),
        },
        downloadLogsTemplate,
    ],
};
const darwinTemplate = {
    label: `&${config_1.config.name}`,
    submenu: [
        aboutTemplate,
        separatorTemplate,
        {
            accelerator: 'Command+,',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.PREFERENCES.SHOW),
            label: locale.getText('menuPreferences'),
        },
        separatorTemplate,
        localeTemplate,
        {
            label: locale.getText('menuServices'),
            role: 'services',
            submenu: [],
        },
        separatorTemplate,
        {
            label: locale.getText('menuHideApp'),
            role: 'hide',
        },
        {
            label: locale.getText('menuHideOthers'),
            role: 'hideOthers',
        },
        {
            label: locale.getText('menuShowAll'),
            role: 'unhide',
        },
        separatorTemplate,
        spellingTemplate,
        separatorTemplate,
        signOutTemplate,
        {
            accelerator: 'Command+Q',
            click: () => lifecycle.quit(),
            label: locale.getText('menuQuit'),
        },
    ],
};
const win32Template = {
    label: `&${config_1.config.name}`,
    submenu: [
        {
            accelerator: 'Ctrl+,',
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.PREFERENCES.SHOW),
            label: locale.getText('menuSettings'),
        },
        localeTemplate,
        toggleAutoLaunchTemplate,
        separatorTemplate,
        spellingTemplate,
        separatorTemplate,
        signOutTemplate,
        {
            accelerator: 'Alt+F4',
            click: () => lifecycle.quit(),
            label: locale.getText('menuQuit'),
        },
    ],
};
const linuxTemplate = {
    label: `&${config_1.config.name}`,
    submenu: [
        toggleAutoLaunchTemplate,
        separatorTemplate,
        localeTemplate,
        separatorTemplate,
        spellingTemplate,
        separatorTemplate,
        signOutTemplate,
        {
            accelerator: 'Ctrl+Q',
            click: () => lifecycle.quit(),
            label: locale.getText('menuQuit'),
        },
    ],
};
const processMenu = (template, language) => {
    for (const item of template) {
        if (item.submenu) {
            processMenu(item.submenu, language);
        }
        if (locale.SUPPORTED_LANGUAGES[language] === item.label) {
            item.checked = true;
        }
    }
};
const showRestartMessageBox = () => __awaiter(void 0, void 0, void 0, function* () {
    const { response } = yield electron_1.dialog.showMessageBox({
        buttons: [
            locale.getText('restartLater'),
            EnvironmentUtil.platform.IS_MAC_OS ? locale.getText('menuQuit') : locale.getText('restartNow'),
        ],
        message: locale.getText('restartLocale'),
        title: locale.getText('restartNeeded'),
        type: 'info',
    });
    if (response === 1) {
        yield (EnvironmentUtil.platform.IS_MAC_OS ? lifecycle.quit() : lifecycle.relaunch());
    }
});
const changeLocale = (language) => __awaiter(void 0, void 0, void 0, function* () {
    locale.setLocale(language);
    yield showRestartMessageBox();
});
const createMenu = (isFullScreen) => {
    const menuTemplate = [conversationTemplate, editTemplate, windowTemplate, helpTemplate];
    if (EnvironmentUtil.platform.IS_MAC_OS) {
        menuTemplate.unshift(darwinTemplate);
        if (Array.isArray(windowTemplate.submenu)) {
            windowTemplate.submenu.push(separatorTemplate, showWireTemplate, separatorTemplate, toggleFullScreenTemplate);
        }
        toggleFullScreenTemplate.checked = isFullScreen;
    }
    if (EnvironmentUtil.platform.IS_WINDOWS) {
        menuTemplate.unshift(win32Template);
        windowTemplate.label = locale.getText('menuView');
        if (Array.isArray(windowTemplate.submenu)) {
            windowTemplate.submenu.unshift(toggleMenuTemplate, separatorTemplate);
        }
    }
    if (EnvironmentUtil.platform.IS_LINUX && Array.isArray(windowTemplate.submenu)) {
        const muteAccelerator = 'Ctrl+Alt+M';
        const muteShortcut = {
            accelerator: muteAccelerator,
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.TOGGLE_MUTE),
            label: 'Toggle mute',
            visible: false,
        };
        const switchShortcuts = Array.from({ length: config_1.config.maximumAccounts }, (_key, index) => {
            const switchAccelerator = `Ctrl+${index + 1}`;
            return {
                accelerator: switchAccelerator,
                click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.ACTION.SWITCH_ACCOUNT, index),
                label: `Switch to Account ${index + 1}`,
                visible: false,
            };
        });
        windowTemplate.submenu.push(muteShortcut, ...switchShortcuts);
        menuTemplate.unshift(linuxTemplate);
        if (Array.isArray(editTemplate.submenu)) {
            editTemplate.submenu.push(separatorTemplate, {
                accelerator: 'Ctrl+,',
                click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.PREFERENCES.SHOW),
                label: locale.getText('menuPreferences'),
            });
        }
        if (Array.isArray(windowTemplate.submenu)) {
            windowTemplate.submenu.push(separatorTemplate, toggleMenuTemplate, separatorTemplate, toggleFullScreenTemplate);
        }
        toggleFullScreenTemplate.checked = isFullScreen;
    }
    if (!EnvironmentUtil.platform.IS_MAC_OS) {
        if (Array.isArray(helpTemplate.submenu)) {
            helpTemplate.submenu.push(separatorTemplate, aboutTemplate);
        }
    }
    processMenu(menuTemplate, locale.getCurrent());
    return electron_1.Menu.buildFromTemplate(menuTemplate);
};
exports.createMenu = createMenu;
const toggleMenuBar = () => {
    const mainBrowserWindow = WindowManager_1.WindowManager.getPrimaryWindow();
    if (mainBrowserWindow) {
        const autoHide = mainBrowserWindow.isMenuBarAutoHide();
        mainBrowserWindow.setAutoHideMenuBar(!autoHide);
        mainBrowserWindow.setMenuBarVisibility(autoHide);
        ConfigurationPersistence_1.settings.save(SettingsType_1.SettingsType.SHOW_MENU_BAR, autoHide);
    }
};
exports.toggleMenuBar = toggleMenuBar;
const toggleSpellChecking = () => __awaiter(void 0, void 0, void 0, function* () {
    const enableSpellChecking = ConfigurationPersistence_1.settings.restore(SettingsType_1.SettingsType.ENABLE_SPELL_CHECKING, true);
    ConfigurationPersistence_1.settings.save(SettingsType_1.SettingsType.ENABLE_SPELL_CHECKING, !enableSpellChecking);
    yield showRestartMessageBox();
});
exports.toggleSpellChecking = toggleSpellChecking;
const registerGlobalShortcuts = () => {
    if (!EnvironmentUtil.platform.IS_LINUX) {
        const muteAccelerator = 'CmdOrCtrl+Alt+M';
        logger.info(`Registering global mute shortcut "${muteAccelerator}" ...`);
        electron_1.globalShortcut.register(muteAccelerator, () => WindowManager_1.WindowManager.sendActionToPrimaryWindow(eventType_1.EVENT_TYPE.UI.SYSTEM_MENU, eventType_1.EVENT_TYPE.CONVERSATION.TOGGLE_MUTE));
        Array.from({ length: config_1.config.maximumAccounts }, (_key, index) => {
            const switchAccelerator = `CmdOrCtrl+${index + 1}`;
            logger.info(`Registering global account switching shortcut "${switchAccelerator}" ...`);
            electron_1.globalShortcut.register(switchAccelerator, () => {
                WindowManager_1.WindowManager.sendActionToPrimaryWindow(eventType_1.EVENT_TYPE.ACTION.SWITCH_ACCOUNT, index);
            });
        });
    }
};
exports.registerGlobalShortcuts = registerGlobalShortcuts;
const unregisterGlobalShortcuts = () => {
    if (!EnvironmentUtil.platform.IS_LINUX) {
        logger.info('Unregistering all global shortcuts ...');
        electron_1.globalShortcut.unregisterAll();
    }
};
exports.unregisterGlobalShortcuts = unregisterGlobalShortcuts;
//# sourceMappingURL=system.js.map