"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupNativefierWindow = exports.onWillPreventUnload = exports.onWillNavigate = exports.onNewWindowHelper = exports.onNewWindow = void 0;
const electron_1 = require("electron");
const helpers_1 = require("./helpers");
const log = __importStar(require("./loggingHelper"));
const windowHelpers_1 = require("./windowHelpers");
function onNewWindow(options, setupWindow, details, parent) {
    log.debug('onNewWindow', {
        details,
    });
    return onNewWindowHelper(options, setupWindow, details, (0, helpers_1.nativeTabsSupported)() ? undefined : parent);
}
exports.onNewWindow = onNewWindow;
function onNewWindowHelper(options, setupWindow, details, parent) {
    log.debug('onNewWindowHelper', {
        options,
        details,
    });
    try {
        if (!(0, helpers_1.linkIsInternal)(options.targetUrl, details.url, options.internalUrls, options.strictInternalUrls)) {
            if (options.blockExternalUrls) {
                (0, windowHelpers_1.showNavigationBlockedMessage)(`Navigation to external URL blocked by options: ${details.url}`)
                    .then(() => {
                    // blockExternalURL(details.url).then(resolve).catch((err: unknown) => {
                    //   log.error('blockExternalURL', err);
                    // });
                })
                    .catch((err) => {
                    throw err;
                });
                return { action: 'deny' };
            }
            else {
                (0, helpers_1.openExternal)(details.url).catch((err) => {
                    log.error('openExternal', err);
                });
                return { action: 'deny' };
            }
        }
        // Normally the following would be:
        // if (urlToGo.startsWith('about:blank'))...
        // But due to a bug we resolved in https://github.com/nativefier/nativefier/issues/1197
        // Some sites use about:blank#something to use as placeholder windows to fill
        // with content via JavaScript. So we'll stay specific for now...
        else if (['about:blank', 'about:blank#blocked'].includes(details.url)) {
            (0, windowHelpers_1.createAboutBlankWindow)(options, setupWindow, (0, helpers_1.nativeTabsSupported)() ? undefined : parent);
            return { action: 'deny' };
        }
        else if ((0, helpers_1.nativeTabsSupported)()) {
            (0, windowHelpers_1.createNewTab)(options, setupWindow, details.url, details.disposition === 'foreground-tab');
            return { action: 'deny' };
        }
        return { action: 'allow' };
    }
    catch (err) {
        return { action: 'deny' };
    }
}
exports.onNewWindowHelper = onNewWindowHelper;
function onWillNavigate(options, event, urlToGo) {
    log.debug('onWillNavigate', urlToGo);
    if (!(0, helpers_1.linkIsInternal)(options.targetUrl, urlToGo, options.internalUrls, options.strictInternalUrls)) {
        event.preventDefault();
        if (options.blockExternalUrls) {
            return new Promise((resolve) => {
                (0, windowHelpers_1.showNavigationBlockedMessage)(`Navigation to external URL blocked by options: ${urlToGo}`)
                    .then(() => resolve())
                    .catch((err) => {
                    throw err;
                });
            });
        }
        else {
            return (0, helpers_1.openExternal)(urlToGo);
        }
    }
    return Promise.resolve(undefined);
}
exports.onWillNavigate = onWillNavigate;
function onWillPreventUnload(event) {
    var _a;
    log.debug('onWillPreventUnload', event);
    const webContents = event.sender;
    if (!webContents) {
        return;
    }
    const browserWindow = (_a = electron_1.BrowserWindow.fromWebContents(webContents)) !== null && _a !== void 0 ? _a : electron_1.BrowserWindow.getFocusedWindow();
    if (browserWindow) {
        const choice = electron_1.dialog.showMessageBoxSync(browserWindow, {
            type: 'question',
            buttons: ['Proceed', 'Stay'],
            message: 'You may have unsaved changes, are you sure you want to proceed?',
            title: 'Changes you made may not be saved.',
            defaultId: 0,
            cancelId: 1,
        });
        if (choice === 0) {
            event.preventDefault();
        }
    }
}
exports.onWillPreventUnload = onWillPreventUnload;
function setupNativefierWindow(options, window) {
    if (options.proxyRules) {
        (0, windowHelpers_1.setProxyRules)(window, options.proxyRules);
    }
    (0, windowHelpers_1.injectCSS)(window);
    window.webContents.on('will-navigate', (event, url) => {
        onWillNavigate(options, event, url).catch((err) => {
            log.error('window.webContents.on.will-navigate ERROR', err);
            event.preventDefault();
        });
    });
    window.webContents.on('will-prevent-unload', onWillPreventUnload);
    (0, windowHelpers_1.sendParamsOnDidFinishLoad)(options, window);
}
exports.setupNativefierWindow = setupNativefierWindow;
//# sourceMappingURL=windowEvents.js.map