"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var _a = require('electron'), ipcMain = _a.ipcMain, BrowserWindow = _a.BrowserWindow, screen = _a.screen;
var _b = require('./childWindow'), newWins = _b.newWins, openNewWindow = _b.openNewWindow, getExcludeWindowList = _b.getExcludeWindowList;
var _c = require('../constant'), MINI_WIDTH = _c.MINI_WIDTH, MINI_HEIGHT = _c.MINI_HEIGHT, isWin32 = _c.isWin32;
var _d = require('../utils/popup'), showElectronPopover = _d.showElectronPopover, hideElectronPopover = _d.hideElectronPopover, updateElectronPopover = _d.updateElectronPopover;
var LEFT_DRAWER_WIDTH = 370;
var EventType = {
    OpenChatroomOrMemberList: 'openChatroomOrMemberList',
    OpenChatroomOrMemberListReply: 'openChatroomOrMemberList-reply',
    FocusWindow: 'focusWindow',
    AnnotationWindow: 'annotationWindow',
    InterpreterWindowChange: 'interpreterWindowChange',
    CaptionWindowChange: 'captionWindowChange',
    ChangeSetting: 'changeSetting',
    IgnoreMouseEvents: 'ignoreMouseEvents',
    ShowPopover: 'showPopover',
    HidePopover: 'hidePopover',
    UpdatePopover: 'updatePopover',
    GetExcludeWindowList: 'getExcludeWindowList',
};
var currentWindow = null;
var preFloatingWindow = false;
// 记录打开侧边栏前的窗口尺寸，用于在最大化状态下关闭侧边栏时恢复
var boundsBeforeSidebar = null;
function focusWindow(event, url) {
    var win = BrowserWindow.fromWebContents(event.sender);
    if (win === currentWindow) {
        if (url === 'mainWindow') {
            win.show();
        }
        else if (newWins[url] && !newWins[url].isDestroyed()) {
            openNewWindow(url, win);
            newWins[url].show();
        }
    }
}
function changeSetting(_, setting) {
    if (currentWindow && !currentWindow.isDestroyed()) {
        currentWindow.webContents.send('changeSetting', setting);
    }
    Object.values(newWins).forEach(function (win) {
        if (win && !win.isDestroyed()) {
            win.webContents.send('changeSetting', setting);
        }
    });
}
var annotationWindowSetBoundsTimer = null;
function annotationWindow(_, data) {
    var annotationWindow = newWins['#/annotation'];
    if (annotationWindow && !annotationWindow.isDestroyed()) {
        var event = data.event, payload_1 = data.payload;
        if (event === 'setBounds') {
            if (!isWin32) {
                var primaryDisplay = screen.getPrimaryDisplay();
                payload_1.y =
                    primaryDisplay.bounds.y +
                        primaryDisplay.bounds.height -
                        payload_1.height -
                        payload_1.y;
            }
            if (payload_1.width < 60 || payload_1.height < 60) {
                // 非 win 平台不透明, 这里是处理 mac 平台最小化后的情况
                if (!isWin32) {
                    annotationWindow.setOpacity(0);
                }
            }
            else {
                if (isWin32) {
                    if (annotationWindowSetBoundsTimer) {
                        clearTimeout(annotationWindowSetBoundsTimer);
                        annotationWindowSetBoundsTimer = null;
                    }
                    var mousePosition = screen.getCursorScreenPoint();
                    var nowDisplay = screen.getDisplayNearestPoint(mousePosition);
                    var scaleFactor_1 = nowDisplay.scaleFactor;
                    annotationWindowSetBoundsTimer = setTimeout(function () {
                        payload_1.x = Math.round(payload_1.x / scaleFactor_1);
                        payload_1.y = Math.round(payload_1.y / scaleFactor_1);
                        payload_1.width = Math.round(payload_1.width / scaleFactor_1);
                        payload_1.height = Math.round(payload_1.height / scaleFactor_1);
                        annotationWindow.setBounds(payload_1, true);
                    }, 300);
                }
                else {
                    annotationWindow.setOpacity(1);
                    annotationWindow.setBounds(payload_1);
                }
            }
        }
        else if (event === 'setIgnoreMouseEvents') {
            annotationWindow.setIgnoreMouseEvents(payload_1);
        }
    }
}
function captionWindowChange(_, data) {
    var newWin = newWins['#/captionWindow'];
    if (!newWin) {
        console.log('captionWindowChange: newWin is null');
    }
    var height = data.height;
    newWin.setBounds({
        height: height,
    });
}
function interpreterWindowChange(_, data) {
    var newWin = newWins['#/interpreterWindow'];
    if (!newWin) {
        console.log('interpreterWindowChange: newWin is null');
    }
    var width = data.width, height = data.height, floatingWindow = data.floatingWindow;
    var nowDisplay = screen.getPrimaryDisplay();
    var _a = nowDisplay.workArea, workWidth = _a.width, workHeight = _a.height;
    if (floatingWindow) {
        newWin.setBounds({
            x: workWidth - 42,
            y: workHeight - 230,
            width: width,
            height: height,
        });
    }
    else {
        if (preFloatingWindow) {
            newWin.setBounds({
                x: workWidth - 225,
                y: workHeight - 390,
                width: width,
                height: height,
            });
        }
        else {
            newWin.setBounds({
                width: width,
                height: height,
            });
        }
    }
    preFloatingWindow = floatingWindow;
}
var setIgnoreMouseEventsTimer = null;
function handleIgnoreMouseEvents(event, data) {
    var win = BrowserWindow.fromWebContents(event.sender);
    setIgnoreMouseEventsTimer && clearTimeout(setIgnoreMouseEventsTimer);
    if (data) {
        win.setIgnoreMouseEvents(true, { forward: true });
        setIgnoreMouseEventsTimer = setTimeout(function () {
            win.setIgnoreMouseEvents(false, { forward: true });
        }, 1000);
    }
    else {
        win.setIgnoreMouseEvents(false, { forward: true });
    }
}
function showPopover(event, items) {
    var mainWindow = BrowserWindow.fromWebContents(event.sender);
    showElectronPopover(items, mainWindow);
}
function hidePopover() {
    hideElectronPopover();
}
function updatePopover(event, items) {
    var mainWindow = BrowserWindow.fromWebContents(event.sender);
    updateElectronPopover(items, mainWindow);
}
function addIpcMainListeners(window) {
    currentWindow = window;
    // 监听窗口取消最大化事件，调整窗口尺寸
    window.on('unmaximize', function () {
        if (boundsBeforeSidebar) {
            // 取消最大化后，如果有记录的尺寸，立即恢复
            setTimeout(function () {
                if (!window.isMaximized() && boundsBeforeSidebar) {
                    window.setBounds(boundsBeforeSidebar);
                    boundsBeforeSidebar = null;
                }
            }, 0);
        }
    });
    // let alreadySetWidth = false
    ipcMain.on(EventType.FocusWindow, focusWindow);
    ipcMain.on(EventType.AnnotationWindow, annotationWindow);
    ipcMain.on(EventType.InterpreterWindowChange, interpreterWindowChange);
    ipcMain.on(EventType.CaptionWindowChange, captionWindowChange);
    ipcMain.on(EventType.OpenChatroomOrMemberList, function (event, isOpen) {
        var mainWindow = BrowserWindow.fromWebContents(event.sender);
        if (!mainWindow) {
            return;
        }
        // 修复windows高缩放比例情况下，打开侧边栏超出屏幕问题
        var mainWindowBounds = mainWindow.getBounds();
        var _a = screen.getDisplayMatching(mainWindowBounds).workArea, displayW = _a.width, displayX = _a.x;
        if (isOpen) {
            mainWindow.setMinimumSize(Math.min(MINI_WIDTH + LEFT_DRAWER_WIDTH, displayW), MINI_HEIGHT);
        }
        else {
            mainWindow.setMinimumSize(Math.min(MINI_WIDTH, displayW), MINI_HEIGHT);
        }
        mainWindow === null || mainWindow === void 0 ? void 0 : mainWindow.webContents.send('openChatroomOrMemberList-reply', isOpen);
        var isMaximizedOrFullScreen = (mainWindow === null || mainWindow === void 0 ? void 0 : mainWindow.isFullScreen()) ||
            (mainWindow === null || mainWindow === void 0 ? void 0 : mainWindow.isMaximized()) ||
            (mainWindow === null || mainWindow === void 0 ? void 0 : mainWindow.isFullScreenPrivate) ||
            (mainWindow === null || mainWindow === void 0 ? void 0 : mainWindow.isMaximizedPrivate);
        // 如果是打开侧边栏，记录当前窗口尺寸
        if (isOpen && !isMaximizedOrFullScreen) {
            boundsBeforeSidebar = __assign({}, mainWindowBounds);
        }
        // 如果是最大化或全屏状态，不修改窗口
        if (isMaximizedOrFullScreen) {
            // 关闭侧边栏时保持记录，等待 unmaximize 事件触发时恢复
            return;
        }
        var mainX = mainWindowBounds.x, mainW = mainWindowBounds.width; // 当前窗口的大小
        if (isOpen) {
            // alreadySetWidth = true
            var newWidth = mainW + LEFT_DRAWER_WIDTH;
            var exceedW = newWidth + mainX - (displayX + displayW);
            if (exceedW > 0) {
                mainWindow.setBounds({
                    x: Math.round(mainX - exceedW),
                    width: Math.round(newWidth),
                });
            }
            else {
                mainWindow.setBounds({
                    width: Math.round(newWidth),
                });
            }
        }
        else {
            // alreadySetWidth = false
            // 如果有记录的尺寸，直接恢复
            if (boundsBeforeSidebar) {
                mainWindow.setBounds(boundsBeforeSidebar);
                boundsBeforeSidebar = null;
            }
            else {
                // 否则按照之前的逻辑计算
                var newWidth = mainW - LEFT_DRAWER_WIDTH;
                // 确保新宽度不超过屏幕宽度
                var finalWidth = Math.min(newWidth, displayW);
                var exceedW = finalWidth + mainX - (displayX + displayW);
                if (exceedW > 0) {
                    mainWindow.setBounds({
                        x: Math.round(mainX - exceedW),
                        width: Math.round(finalWidth),
                    });
                }
                else {
                    mainWindow.setBounds({
                        width: Math.round(finalWidth),
                    });
                }
            }
        }
        event.sender.send(EventType.OpenChatroomOrMemberListReply);
    });
    ipcMain.on(EventType.ChangeSetting, changeSetting);
    ipcMain.on(EventType.IgnoreMouseEvents, handleIgnoreMouseEvents);
    ipcMain.on(EventType.ShowPopover, showPopover);
    ipcMain.on(EventType.HidePopover, hidePopover);
    ipcMain.on(EventType.UpdatePopover, updatePopover);
    ipcMain.removeHandler(EventType.GetExcludeWindowList);
    ipcMain.handle(EventType.GetExcludeWindowList, function () {
        return getExcludeWindowList();
    });
}
function removeIpcMainListeners() {
    ipcMain.removeListener(EventType.FocusWindow, focusWindow);
    ipcMain.removeListener(EventType.AnnotationWindow, annotationWindow);
    ipcMain.removeListener(EventType.InterpreterWindowChange, interpreterWindowChange);
    ipcMain.removeListener(EventType.CaptionWindowChange, captionWindowChange);
    ipcMain.removeListener(EventType.changeSetting, changeSetting);
    ipcMain.removeAllListeners(EventType.OpenChatroomOrMemberList);
    ipcMain.removeListener(EventType.IgnoreMouseEvents, handleIgnoreMouseEvents);
    ipcMain.removeListener(EventType.ShowPopover, showPopover);
    ipcMain.removeListener(EventType.HidePopover, hidePopover);
    ipcMain.removeListener(EventType.UpdatePopover, updatePopover);
    ipcMain.removeHandler(EventType.GetExcludeWindowList);
}
module.exports = {
    addIpcMainListeners: addIpcMainListeners,
    removeIpcMainListeners: removeIpcMainListeners,
};