"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = openMicrosoftWindow;
const path_1 = __importDefault(require("path"));
const electron_1 = require("electron");
const defaultProperties = {
    width: 1000,
    height: 650,
    resizable: false,
    center: true,
    icon: path_1.default.join(__dirname, '../../../resources/icons', `microsoft.${process.platform === 'win32' ? 'ico' : 'png'}`),
};
async function openMicrosoftWindow(url) {
    await new Promise((resolve) => {
        electron_1.app.whenReady().then(() => {
            electron_1.session.defaultSession.cookies.get({ domain: 'live.com' }).then((cookies) => {
                for (const cookie of cookies) {
                    const urlcookie = `http${cookie.secure ? 's' : ''}://${cookie.domain.replace(/^\./, '') + cookie.path}`;
                    electron_1.session.defaultSession.cookies.remove(urlcookie, cookie.name);
                }
            });
            resolve();
        });
    });
    return new Promise((resolve) => {
        electron_1.app.whenReady().then(() => {
            const mainWindow = new electron_1.BrowserWindow(defaultProperties);
            mainWindow.setMenu(null);
            mainWindow.loadURL(url);
            let loading = false;
            mainWindow.webContents.setWindowOpenHandler(() => {
                return { action: "deny" };
            });
            const allowedDomains = [
                "https://login.live.com",
                "https://login.microsoftonline.com",
                "https://login.live-int.com",
                "https://login.microsoft.com",
                "https://login.live.com/oauth20_desktop.srf"
            ];
            mainWindow.webContents.on("will-navigate", (event, navigationUrl) => {
                if (!allowedDomains.some(domain => navigationUrl.startsWith(domain))) {
                    event.preventDefault();
                    console.log("Bloqueado:", navigationUrl);
                }
            });
            mainWindow.on('close', () => {
                if (!loading)
                    resolve(null);
            });
            mainWindow.webContents.on('did-finish-load', () => {
                const loc = mainWindow.webContents.getURL();
                if (loc.startsWith('https://login.live.com/oauth20_desktop.srf')) {
                    const code = new URLSearchParams(loc.split('?')[1]).get('code');
                    resolve(code ?? null);
                    loading = true;
                    try {
                        mainWindow.close();
                    }
                    catch {
                        console.error('Failed to close window!');
                    }
                }
            });
        });
    });
}
