"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const path_1 = __importDefault(require("path"));
// --- Propiedades de la ventana ---
const defaultProperties = {
    width: 1000,
    height: 650,
    resizable: false,
    position: "center",
    frame: true,
    icon: path_1.default.join(__dirname, "../../../resources/icons/microsoft.png")
};
module.exports = async function (url) {
    // --- Limpiar cookies ---
    await new Promise((resolve) => {
        nw.Window.get().cookies.getAll({ domain: "live.com" }, (cookies) => {
            for (const cookie of cookies) {
                const cookieUrl = `http${cookie.secure ? "s" : ""}://${cookie.domain.replace(/^\./, "") + cookie.path}`;
                nw.Window.get().cookies.remove({ url: cookieUrl, name: cookie.name });
            }
            resolve();
        });
    });
    // --- Abrir ventana y capturar el código ---
    const code = await new Promise((resolve) => {
        nw.Window.open(url, defaultProperties, (Window) => {
            let intervalId;
            let authCode = null;
            intervalId = Window.window.setInterval(() => {
                try {
                    const href = Window.window.document.location.href;
                    if (href.startsWith("https://login.live.com/oauth20_desktop.srf")) {
                        if (intervalId !== undefined)
                            Window.window.clearInterval(intervalId);
                        authCode = href.split("code=")[1]?.split("&")[0] || "cancel";
                        Window.close();
                    }
                }
                catch {
                    authCode = "cancel";
                }
            }, 100);
            Window.on("closed", () => {
                if (!authCode)
                    authCode = "cancel";
                if (intervalId !== undefined)
                    Window.window.clearInterval(intervalId);
                resolve(authCode);
            });
        });
    });
    return code;
};
