"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerPowerMonitor = registerPowerMonitor;
exports.unregisterPowerMonitor = unregisterPowerMonitor;
var child_process_1 = require("child_process");
var electron_1 = require("electron");
var os = require("os");
var IPC_EVENT = {
    POWER_MONITOR_SYSTEM_LOCK: 'POWER_MONITOR_SYSTEM_LOCK',
    POWER_MONITOR_SYSTEM_UNLOCK: 'POWER_MONITOR_SYSTEM_UNLOCK',
};
var mainWindow = null;
var dbusProcess = null;
var lastActivityCheck = null;
var isLocked = false;
function handleSystemLock() {
    console.log('handleSystemLock');
    if (!mainWindow || mainWindow.isDestroyed())
        return;
    isLocked = true;
    mainWindow.webContents.send(IPC_EVENT.POWER_MONITOR_SYSTEM_LOCK);
}
function handleSystemUnlock() {
    console.log('handleSystemUnlock');
    if (!mainWindow || mainWindow.isDestroyed())
        return;
    isLocked = false;
    mainWindow.webContents.send(IPC_EVENT.POWER_MONITOR_SYSTEM_UNLOCK);
}
// Linux 下使用 D-Bus 监听锁屏事件
function setupLinuxScreenLockMonitor() {
    var _a;
    if (os.platform() !== 'linux')
        return;
    console.log('Setting up Linux screen lock monitor via D-Bus');
    // 尝试监听 GNOME 锁屏事件
    var gnomeDbusMonitor = (0, child_process_1.spawn)('dbus-monitor', [
        '--session',
        "type='signal',interface='org.gnome.ScreenSaver',member='ActiveChanged'",
    ]);
    (_a = gnomeDbusMonitor.stdout) === null || _a === void 0 ? void 0 : _a.on('data', function (data) {
        var output = data.toString();
        if (output.includes('boolean true')) {
            handleSystemLock();
        }
        else if (output.includes('boolean false')) {
            handleSystemUnlock();
        }
    });
    gnomeDbusMonitor.on('error', function (error) {
        console.log('GNOME D-Bus monitor failed, trying KDE:', error.message);
        setupKDEScreenLockMonitor();
    });
    dbusProcess = gnomeDbusMonitor;
}
// KDE 锁屏监听
function setupKDEScreenLockMonitor() {
    var _a;
    var kdeDbusMonitor = (0, child_process_1.spawn)('dbus-monitor', [
        '--session',
        "type='signal',interface='org.freedesktop.ScreenSaver',member='ActiveChanged'",
    ]);
    (_a = kdeDbusMonitor.stdout) === null || _a === void 0 ? void 0 : _a.on('data', function (data) {
        var output = data.toString();
        if (output.includes('boolean true')) {
            handleSystemLock();
        }
        else if (output.includes('boolean false')) {
            handleSystemUnlock();
        }
    });
    kdeDbusMonitor.on('error', function (error) {
        console.log('KDE D-Bus monitor failed, using fallback method:', error.message);
        setupFallbackActivityMonitor();
    });
    dbusProcess = kdeDbusMonitor;
}
// 备用方案：通过检查用户活动状态
function setupFallbackActivityMonitor() {
    console.log('Using fallback activity monitor for Linux');
    var lastActiveTime = Date.now();
    var wasActive = true;
    var checkActivity = function () {
        // 检查是否有键盘/鼠标活动的简单方法
        // 这里可以通过检查 /proc/interrupts 或其他系统信息来判断
        var currentTime = Date.now();
        // 如果超过 30 秒没有活动，可能是锁屏了
        var timeSinceLastActivity = currentTime - lastActiveTime;
        var isCurrentlyActive = timeSinceLastActivity < 30000;
        if (wasActive && !isCurrentlyActive && !isLocked) {
            // 从活跃状态变为非活跃状态，可能是锁屏
            setTimeout(function () {
                if (!isLocked && timeSinceLastActivity > 60000) {
                    handleSystemLock();
                }
            }, 5000);
        }
        else if (!wasActive && isCurrentlyActive && isLocked) {
            // 从非活跃状态变为活跃状态，可能是解锁
            handleSystemUnlock();
        }
        wasActive = isCurrentlyActive;
        if (isCurrentlyActive) {
            lastActiveTime = currentTime;
        }
    };
    lastActivityCheck = setInterval(checkActivity, 5000);
}
// 清理 Linux 监听器
function cleanupLinuxMonitor() {
    if (dbusProcess) {
        dbusProcess.kill();
        dbusProcess = null;
    }
    if (lastActivityCheck) {
        clearInterval(lastActivityCheck);
        lastActivityCheck = null;
    }
}
function registerPowerMonitor(mWin) {
    console.log('registerPowerMonitor');
    mainWindow = mWin;
    // 注册标准的 powerMonitor 事件（适用于 Windows 和 macOS）
    electron_1.powerMonitor.on('lock-screen', handleSystemLock);
    electron_1.powerMonitor.on('unlock-screen', handleSystemUnlock);
    electron_1.powerMonitor.on('suspend', handleSystemLock);
    electron_1.powerMonitor.on('resume', handleSystemUnlock);
    // Linux 下的特殊处理
    if (os.platform() === 'linux') {
        setupLinuxScreenLockMonitor();
    }
}
function unregisterPowerMonitor() {
    mainWindow = null;
    electron_1.powerMonitor.off('lock-screen', handleSystemLock);
    electron_1.powerMonitor.off('unlock-screen', handleSystemUnlock);
    electron_1.powerMonitor.off('suspend', handleSystemLock);
    electron_1.powerMonitor.off('resume', handleSystemUnlock);
    // 清理 Linux 特有的监听器
    cleanupLinuxMonitor();
}