"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var electron_1 = require("electron");
var path = require("path");
var os = require("os");
var fs = require("fs");
var prefPath = path.join(electron_1.app.getPath('userData'), 'user-preferences.json');
var MIN_WINDOW_WIDTH = 400;
var MIN_WINDOW_HEIGHT = 300;
function getExtensionPref() {
    try {
        var data = fs.readFileSync(prefPath, 'utf8');
        var prefs = JSON.parse(data);
        return prefs.enableExtension;
    }
    catch (_a) {
        console.error('Error reading extension preference:', prefPath);
        return false; // default to false if file missing or error
    }
}
function setExtensionPref(enabled) {
    try {
        fs.writeFileSync(prefPath, JSON.stringify({ enableExtension: enabled }));
    }
    catch (error) {
        console.error('Error setting extension preference:', error);
    }
}
// Add secure storage handlers
var SECURE_STORAGE_PATH = path.join(electron_1.app.getPath('userData'), 'secure-storage.json');
var isMac = os.platform() === 'darwin';
var isWindows = os.platform() === 'win32';
var si = require('systeminformation');
electron_1.app.commandLine.appendSwitch('disable-renderer-backgrounding');
electron_1.app.commandLine.appendSwitch('disable-background-timer-throttling');
electron_1.app.commandLine.appendSwitch('disable-backgrounding-occluded-windows');
// Example: Get basic system info and log it
var systemInformationQueryObject = {
    cpu: 'manufacturer, brand, vendor, speed, cores, family, model',
    system: '*',
    mem: 'total, free, available',
    osInfo: 'platform, release',
    // graphics: '*',
};
// si.system();
// si.get(systemInformationQueryObject)
//   .then((data) => {
//     console.log('System Info:', data);
//     // const displays = data.displays;
//     // // displays is an array, one object per connected screen
//     // displays.forEach((display, i) => {
//     //   console.log(`Display ${i}:`, {
//     //     vendor: display.vendor,
//     //     model: display.model,
//     //     main: display.main, // is primary
//     //     builtin: display.builtin, // laptop panel
//     //     connection: display.connection, // 'HDMI-1', 'DP-1', etc.
//     //     resolutionX: display.resolutionX, // native resolution
//     //     resolutionY: display.resolutionY,
//     //     currentResX: display.currentResX, // active resolution
//     //     currentResY: display.currentResY,
//     //     currentRefreshRate: display.currentRefreshRate,
//     //     pixelDepth: display.pixelDepth,
//     //     sizeX: display.sizeX, // physical size mm
//     //     sizeY: display.sizeY,
//     //     positionX: display.positionX, // virtual desktop coords
//     //     positionY: display.positionY,
//     //   });
//     // });
//   })
//   .catch((error) => {
//     console.error('System Info Error:', error);
//   });
if (isMac === true) {
    var microphone = electron_1.systemPreferences.askForMediaAccess('microphone');
    var camera = electron_1.systemPreferences.askForMediaAccess('camera');
    console.log('microphone', microphone);
    console.log('camera', camera);
}
var mainWindow = null;
var oauthWindow = null;
var deeplinkingUrl = null;
var appURL = 'https://app.vqvelocity.com';
// const appURL = 'http://localhost:8100';
var setAlwaysOnTop = false;
var callbackForBluetoothEvent = null;
// let tray;
// const args = process.argv.slice(1);
// const serve = args.some((val) => val === '--serve');
// https://github.com/vuerust/electron-typescript-starter/blob/main/src/main.ts
// https://syobochim.medium.com/electron-keep-apps-on-top-whether-in-full-screen-mode-or-on-other-desktops-d7d914579fce
// if (isMac) {
//   app.dock.hide();
// }
// Log both at dev console and at running node console instance
function logEverywhere(s) {
    console.log(s);
    if (mainWindow && mainWindow.webContents) {
        mainWindow.webContents.executeJavaScript("console.log(\"".concat(s, "\")"));
    }
}
function createWindow() {
    var _this = this;
    console.log('createWindow()');
    console.log('deeplinkingUrl', deeplinkingUrl);
    console.log('isMac', isMac);
    console.log('isWindows', isWindows);
    var size = electron_1.screen.getPrimaryDisplay().workAreaSize;
    // Setup preload script path and construct our main window.
    // const preloadPath = join(app.getAppPath(), 'app', 'preload.js');
    var preloadPath = path.join(electron_1.app.getAppPath(), 'preload.js');
    // Create the browser window.
    mainWindow = new electron_1.BrowserWindow({
        show: false,
        x: 0,
        y: 0,
        width: size.width - 100,
        height: size.height - 100,
        // Velocity App Bar and Transparent Window Opportunity
        transparent: true,
        frame: false,
        // https://github.com/electron/electron/issues/8847
        hasShadow: false, // Added to try and remove the shadow
        thickFrame: false, // false works better with transparent windows on Windows
        // Testing out hidden traffic lights
        // titleBarStyle: 'hidden',
        //MacOS Flag to enable to float top of Full-screened app
        type: 'panel',
        alwaysOnTop: true,
        maximizable: true,
        webPreferences: {
            nodeIntegration: false,
            // contextBridge: true,
            contextIsolation: true,
            preload: preloadPath,
            spellcheck: false,
            // Added to prevent app from falling asleep
            backgroundThrottling: false,
        },
        // webPreferences: {
        //   nodeIntegration: true,
        //   // allowRunningInsecureContent: serve,
        //   // allowRunningInsecureContent: true,
        //   contextIsolation: true,
        //   // preload: `file://${__dirname}/preload.js`, //path.join(__dirname, 'preload.js'),
        // },
    });
    // Added to let the window float on top of full-screened apps
    mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
    if (process.platform === 'darwin') {
        try {
            // mainWindow.setAlwaysOnTop(true, 'screen-saver');
            mainWindow.setAlwaysOnTop(true, 'floating', 1);
            electron_1.app.dock.show();
        }
        catch (error) {
            console.error('Error in app.dock.show()', error);
        }
    }
    // Turn it off for now
    mainWindow.setAlwaysOnTop(false);
    // mainWindow.webContents.openDevTools();
    mainWindow.show();
    // mainWindow.maximize();
    // Load the URL of the app
    if (deeplinkingUrl) {
        // const durl = deeplinkingUrl.replace('velocity://', 'https://');
        var durl = deeplinkingUrl;
        if (deeplinkingUrl.includes('localhost')) {
            durl = deeplinkingUrl.replace('velocity://', 'http://');
        }
        else
            durl = deeplinkingUrl.replace('velocity://', 'https://');
        mainWindow.loadURL(durl);
    }
    else {
        mainWindow.loadURL(appURL);
    }
    // if (true) {
    //   // mainWindow.loadURL('http://localhost:8100');
    //   // mainWindow.loadURL(appURL);
    // } else {
    //   // Path when running electron executable
    //   const pathIndex = 'www/index.html';
    //   // if (fs.existsSync(path.join(__dirname, '../www/index.html'))) {
    //   //   // Path when running electron in local folder
    //   //   pathIndex = '../dist/index.html';
    //   // }
    //   // pathIndex = '../dist/index.html';
    //   console.log('__dirname', __dirname);
    //   console.log('pathIndex', pathIndex);
    //   // const url = new URL(path.join('file:', __dirname, pathIndex));
    //   // win.loadURL(url.href);
    //   pathURL = `file://${__dirname}/${pathIndex}`;
    //   console.log('pathURL', pathURL);
    //   // mainWindow.loadURL(pathURL);
    //   mainWindow.loadFile(`${__dirname}/${pathIndex}`);
    //   // win.loadURL(
    //   //   url.format({
    //   //     pathname: path.join('file:', __dirname, pathIndex),
    //   //     protocol: 'file:',
    //   //     slashes: true,
    //   //   })
    //   // );
    // }
    mainWindow.setBackgroundColor('#00000000');
    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        // Dereference the window object, usually you would store window
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });
    // Added to deal w/ force reload app on browser reload
    mainWindow.webContents.on('did-fail-load', function () {
        renderlog('on browser reload it did-fail-load and reloaded the app');
        // const pathIndex = '../www/index.html';
        // const url = new URL(path.join('file:', __dirname, pathIndex));
        // mainWindow.loadURL(url.href);
        // win.loadURL(file://${__dirname}/dist//index.html);
    });
    mainWindow.once('ready-to-show', function () {
        // Attempt to focus the window
        electron_1.app.focus({ steal: true });
        mainWindow.show();
    });
    // When the web app is loaded we hide the splashscreen if needed and show the mainwindow.
    mainWindow.webContents.on('dom-ready', function () {
        // renderlog('win.webContents.on(dom-ready)');
        mainWindow.show();
        // win.show();
    });
    // Velocity BLE Code to handle bluetooth device selection
    mainWindow.webContents.on('select-bluetooth-device', function (event, deviceList, callback) {
        // console.log("this.MainWindow.webContents.on('select-bluetooth-device'");
        event.preventDefault();
        // Callback handler Reference (typically setup after)
        callbackForBluetoothEvent = callback;
        if (deviceList && deviceList.length > 0) {
            mainWindow.webContents.send('deviceListUpdated', deviceList);
        }
    });
    electron_1.ipcMain.on('deviceSelected', function (event, deviceId) {
        renderlog('electron console : deviceSelected ' + deviceId);
        callbackForBluetoothEvent(deviceId);
    });
    electron_1.ipcMain.on('cancelScan', function (event) {
        console.warn('cancelScan', event);
        renderlog('electron console : cancelScan'); // +event);
        callbackForBluetoothEvent('');
    });
    // Window resize handlers for transparent frameless windows on Windows
    electron_1.ipcMain.on('start-window-resize', function (event, edge) {
        if (mainWindow && isWindows) {
            var _a = mainWindow.getSize(), width = _a[0], height = _a[1];
            var _b = mainWindow.getPosition(), x = _b[0], y = _b[1];
            mainWindow.webContents.send('resize-started', {
                edge: edge,
                x: x,
                y: y,
                width: width,
                height: height,
            });
        }
    });
    electron_1.ipcMain.on('resize-window', function (event, _a) {
        var deltaX = _a.deltaX, deltaY = _a.deltaY, edge = _a.edge;
        if (mainWindow && isWindows) {
            var _b = mainWindow.getSize(), currentWidth = _b[0], currentHeight = _b[1];
            var _c = mainWindow.getPosition(), currentX = _c[0], currentY = _c[1];
            var newWidth = currentWidth;
            var newHeight = currentHeight;
            var newX = currentX;
            var newY = currentY;
            // Handle different resize edges/corners
            if (edge.includes('right')) {
                newWidth = Math.max(MIN_WINDOW_WIDTH, currentWidth + deltaX);
            }
            if (edge.includes('left')) {
                var requestedWidth = currentWidth - deltaX;
                var constrainedWidth = Math.max(MIN_WINDOW_WIDTH, requestedWidth);
                if (constrainedWidth !== currentWidth) {
                    newWidth = constrainedWidth;
                    // Shift X based on the actual width change so the left edge tracks the cursor.
                    newX = currentX + (currentWidth - constrainedWidth);
                }
            }
            if (edge.includes('bottom')) {
                newHeight = Math.max(MIN_WINDOW_HEIGHT, currentHeight + deltaY);
            }
            if (edge.includes('top')) {
                var requestedHeight = currentHeight - deltaY;
                var constrainedHeight = Math.max(MIN_WINDOW_HEIGHT, requestedHeight);
                if (constrainedHeight !== currentHeight) {
                    newHeight = constrainedHeight;
                    // Shift Y based on the actual height change so the top edge tracks the cursor.
                    newY = currentY + (currentHeight - constrainedHeight);
                }
            }
            mainWindow.setBounds({
                x: newX,
                y: newY,
                width: newWidth,
                height: newHeight,
            });
        }
    });
    // Place all ipc or other electron api calls and custom functionality under this line
    electron_1.ipcMain.on('toggle-maximize-window', function (event) {
        console.warn('electron console : toggle-maximize-window', event);
        if (mainWindow.isMaximized() === true) {
            console.warn('electron console : toggle-maximize-window mainWindow.unmaximize()');
            mainWindow.unmaximize();
        }
        else if (mainWindow.isMaximizable() === true) {
            console.warn('electron console : toggle-maximize-window mainWindow.maximize()');
            mainWindow.maximize();
        }
        else {
            console.warn('electron console : toggle-maximize-window else');
            mainWindow.maximize();
        }
    });
    electron_1.ipcMain.on('toggle-fullscreen-window', function (event) {
        console.warn('electron console : toggle-fullscreen-window', event);
        if (mainWindow.isFullScreen() === true) {
            mainWindow.setFullScreen(false);
        }
        else {
            mainWindow.setFullScreen(true);
        }
    });
    electron_1.ipcMain.on('toggle-unmaximize-window', function (event) {
        console.warn('electron console : toggle-unmaximize', event);
        mainWindow.unmaximize();
    });
    electron_1.ipcMain.on('toggle-minimize-window', function (event) {
        console.warn('electron console : toggle-minimize-window', event);
        if (mainWindow.isMinimizable() === true) {
            mainWindow.minimize();
        }
    });
    electron_1.ipcMain.on('close-window', function (event) {
        console.warn('electron console : close-window', event);
        if (mainWindow.isClosable()) {
            mainWindow.close();
        }
        // https://stackoverflow.com/questions/48593064/closing-an-electron-app-on-darwin
        // if (process.platform !== 'darwin') {
        //   app.quit();
        // }
        electron_1.app.quit();
    });
    // https://stackoverflow.com/questions/39835282/set-browserwindow-always-on-top-even-other-app-is-in-fullscreen-electron-mac
    electron_1.ipcMain.on('toggleAlwaysOnTop', function (event, bflag) {
        console.warn('electron console : toggleAlwaysOnTop', bflag);
        console.warn('electron console : toggleAlwaysOnTop', event);
        // Store the always on top flag coming in from the renderer
        setAlwaysOnTop = bflag;
        if (setAlwaysOnTop) {
            // mainWindow.setAlwaysOnTop(bflag, 'floating');
            // mainWindow.setAlwaysOnTop(true, 'screen-saver', 1);
            if (process.platform == 'darwin') {
                mainWindow.setAlwaysOnTop(true, 'screen-saver', 1);
            }
            else {
                mainWindow.setAlwaysOnTop(true, 'screen-saver');
            }
            // mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
        }
        else {
            mainWindow.setAlwaysOnTop(false);
            // mainWindow.setVisibleOnAllWorkspaces(false);
        }
        // Trying to bypass the bug requiring window to be resized to be transparent
        // console.warn('electron console : mainWindow.maximize()');
        // mainWindow.maximize();
        // mainWindow.getBrowserView().setAutoResize({ width: true, height: true });
        // const wh = mainWindow.getSize();
        // console.warn('electron console : windows width', wh[0]);
        // mainWindow.setSize(wh[0] - 10, wh[1], true);
        // const size2 = mainWindow.getSize();
        // console.warn('electron console : windows width', size2[0]);
        // mainWindow.setSize(wh[0] + 10, wh[1], true);
        // mainWindow.center();
    });
    electron_1.ipcMain.on('openDevTools', function (event) {
        console.warn('electron console : openDevTools', event);
        mainWindow.webContents.openDevTools();
    });
    // Click through window functionality
    electron_1.ipcMain.on('set-ignore-mouse-events', function (event, ignore, options) {
        var win = electron_1.BrowserWindow.fromWebContents(event.sender);
        win.setIgnoreMouseEvents(ignore, options);
    });
    // Expose the app version via IPC
    electron_1.ipcMain.handle('get-app-version', function () {
        return electron_1.app.getVersion();
    });
    // Example: Expose system info to renderer via IPC
    electron_1.ipcMain.handle('get-system-info', function () { return __awaiter(_this, void 0, void 0, function () {
        var data, error_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, si.get(systemInformationQueryObject)];
                case 1:
                    data = _a.sent();
                    return [2 /*return*/, data];
                case 2:
                    error_1 = _a.sent();
                    return [2 /*return*/, { error: error_1.message }];
                case 3: return [2 /*return*/];
            }
        });
    }); });
    // Optional: IPC to toggle preference from renderer
    electron_1.ipcMain.handle('set-extension-pref', function (event, enabled) {
        setExtensionPref(enabled);
        electron_1.app.relaunch();
        electron_1.app.exit();
    });
    electron_1.ipcMain.handle('get-extension-pref', function () {
        return getExtensionPref();
    });
    // OAuth Window Handling
    electron_1.ipcMain.on('open-oauth-window', function (event, authUrl) {
        console.warn('electron console : open-oauth-window authUrl', authUrl);
        oauthWindow = new electron_1.BrowserWindow({
            width: 640,
            height: 700,
            x: 200,
            y: 150,
            parent: electron_1.BrowserWindow.getFocusedWindow(),
            // modal: true,
            webPreferences: {
                nodeIntegration: false,
                contextIsolation: true,
                preload: preloadPath,
                spellcheck: false,
                backgroundThrottling: false,
            },
        });
        // Load the Auth URL in the child window
        oauthWindow.loadURL(authUrl);
        // Listen for redirects to the callback URL
        oauthWindow.webContents.on('will-redirect', function (e, url) {
            console.log('');
            console.log('will-redirect ', url);
            var tokenresult = '?token=';
            if (url.includes(tokenresult)) {
                console.log('OAuth redirect tokenresult detected:', url);
                e.preventDefault();
                var urlObj = new URL(url);
                // const token =
                //   urlObj.searchParams.get('token') || urlObj.searchParams.get('code');
                var token = urlObj.searchParams.get('token');
                event.sender.send('oauth-result', token);
                console.log('oauth-result', token);
                oauthWindow.close();
                oauthWindow = null;
            }
        });
        // childWindow.webContents.on('did-navigate', (e, url) => {
        //   console.log('did-navigate ', url);
        // });
        oauthWindow.on('closed', function () {
            event.sender.send('oauth-result', null);
        });
    });
    // Listen for the close command from the renderer
    electron_1.ipcMain.on('close-oauth-window', function (event, fakeAuth) {
        console.warn('');
        console.warn('electron console : fakeAuth', fakeAuth);
        if (oauthWindow) {
            // Send a message back to the renderer that the token was refreshed : mainWindow
            mainWindow.webContents.send('oauth-result', fakeAuth);
            // console.warn('GOING TO CLOSE OAUTH WINDOW, Halted back for testing');
            oauthWindow.close();
            oauthWindow = null;
        }
    });
    // Secure Storage Handlers
    electron_1.ipcMain.handle('secure-storage-set', function (event, key, value) { return __awaiter(_this, void 0, void 0, function () {
        var storage, data, encryptedValue;
        return __generator(this, function (_a) {
            try {
                storage = {};
                if (fs.existsSync(SECURE_STORAGE_PATH)) {
                    data = fs.readFileSync(SECURE_STORAGE_PATH, 'utf8');
                    storage = JSON.parse(data);
                }
                encryptedValue = electron_1.safeStorage.encryptString(value);
                storage[key] = encryptedValue.toString('base64');
                // Save back to file
                fs.writeFileSync(SECURE_STORAGE_PATH, JSON.stringify(storage), 'utf8');
                return [2 /*return*/, true];
            }
            catch (error) {
                console.error('Error setting secure storage:', error);
                return [2 /*return*/, false];
            }
            return [2 /*return*/];
        });
    }); });
    electron_1.ipcMain.handle('secure-storage-get', function (event, key) { return __awaiter(_this, void 0, void 0, function () {
        var data, storage, encryptedBuffer;
        return __generator(this, function (_a) {
            try {
                if (!fs.existsSync(SECURE_STORAGE_PATH)) {
                    return [2 /*return*/, null];
                }
                data = fs.readFileSync(SECURE_STORAGE_PATH, 'utf8');
                storage = JSON.parse(data);
                if (storage[key]) {
                    encryptedBuffer = Buffer.from(storage[key], 'base64');
                    return [2 /*return*/, electron_1.safeStorage.decryptString(encryptedBuffer)];
                }
                return [2 /*return*/, null];
            }
            catch (error) {
                console.error('Error getting secure storage:', error);
                return [2 /*return*/, null];
            }
            return [2 /*return*/];
        });
    }); });
    electron_1.ipcMain.handle('secure-storage-delete', function (event, key) { return __awaiter(_this, void 0, void 0, function () {
        var data, storage;
        return __generator(this, function (_a) {
            try {
                if (!fs.existsSync(SECURE_STORAGE_PATH)) {
                    return [2 /*return*/, true];
                }
                data = fs.readFileSync(SECURE_STORAGE_PATH, 'utf8');
                storage = JSON.parse(data);
                delete storage[key];
                fs.writeFileSync(SECURE_STORAGE_PATH, JSON.stringify(storage), 'utf8');
                return [2 /*return*/, true];
            }
            catch (error) {
                console.error('Error deleting secure storage:', error);
                return [2 /*return*/, false];
            }
            return [2 /*return*/];
        });
    }); });
    // Setting up an internal timer to force the window to be always on top
    setInterval(function () {
        if (mainWindow && setAlwaysOnTop) {
            // Force toggle the flag to force the window to be always on top
            // mainWindow.setAlwaysOnTop(false);
            mainWindow.setAlwaysOnTop(true, 'screen-saver', 1);
        }
    }, 3000);
    return mainWindow;
}
function renderlog(payload) {
    try {
        mainWindow.webContents.send('renderlog', payload);
        console.log('electron console : ', payload);
    }
    catch (error) {
        console.log('electron console : ', error, payload);
    }
}
// Electron Application Initialization
try {
    // https://github.com/electron/electron/blob/v29.1.4/docs/api/app.md#apprequestsingleinstancelockadditionaldata
    // const additionalData = { myKey: 'myValue' };
    var gotTheLock = electron_1.app.requestSingleInstanceLock();
    if (!gotTheLock) {
        electron_1.app.quit();
    }
    else {
        // Deep linking URL from the command line arguments for Windows
        // Loop through the command line arguments
        process.argv.forEach(function (val, index) {
            // dialog.showErrorBox('process.argv ' + index, `val: ${val}`);
            if (val.includes('velocity://')) {
                deeplinkingUrl = val;
                console.log('deeplinkingUrl', deeplinkingUrl, index);
                // dialog.showErrorBox('process.argv ' + index, `val: ${val}`);
            }
        });
        electron_1.app.on('second-instance', function (event, commandLine) {
            // Someone tried to run a second instance, we should focus our window.
            if (mainWindow) {
                if (mainWindow.isMinimized())
                    mainWindow.restore();
                mainWindow.focus();
            }
            // Parse the deep link URL from the command line arguments
            // Protocol handler for win32
            // argv: An array of the second instance’s (command line / deep linked) arguments
            var deepLinkUrl;
            for (var _i = 0, commandLine_1 = commandLine; _i < commandLine_1.length; _i++) {
                var arg = commandLine_1[_i];
                if (arg.startsWith('velocity://')) {
                    deepLinkUrl = arg;
                    break;
                }
            }
            if (deepLinkUrl && mainWindow) {
                var durl = deepLinkUrl;
                if (deepLinkUrl.includes('localhost')) {
                    durl = deepLinkUrl.replace('velocity://', 'http://');
                }
                else {
                    durl = deepLinkUrl.replace('velocity://', 'https://');
                }
                mainWindow.loadURL(durl);
                mainWindow.webContents.send('deep-link-url', durl);
            }
        });
        electron_1.app.on('open-url', function (event, url) {
            event.preventDefault();
            deeplinkingUrl = url;
            logEverywhere('open-url# ' + deeplinkingUrl);
            var durl = deeplinkingUrl;
            if (deeplinkingUrl.includes('localhost')) {
                durl = deeplinkingUrl.replace('velocity://', 'http://');
            }
            else
                durl = deeplinkingUrl.replace('velocity://', 'https://');
            logEverywhere('open-url# durl' + durl);
            // Prevent the default, since we handle it ourselves
            if (durl && mainWindow) {
                mainWindow.loadURL(durl);
                mainWindow.webContents.send('custom-url-opened', durl);
            }
        });
        // app.on('will-finish-launching', () => {
        //   // Protocol handler for osx
        //   app.on('open-url', (event, url) => {
        //     event.preventDefault();
        //     deeplinkingUrl = url;
        //     dialog.showErrorBox(
        //       'Welcome Back open-url',
        //       `You arrived from: ${url}`
        //     );
        //     // this.mainWindow.loadURL(appURL + 'vod/6877');
        //   });
        // });
        // This method will be called when Electron has finished
        // initialization and is ready to create browser windows.
        // Some APIs can only be used after this event occurs.
        // Added 400 ms to fix the black background issue while using transparent window. More detais at https://github.com/electron/electron/issues/15947
        // app.on('ready', () => setTimeout(createWindow, 400));
        electron_1.app.on('ready', function () {
            // renderlog('app.on(ready)');
            // Look at bundling the Streamdeck plugin into the app
            // session.defaultSession
            //   .loadExtension(
            //     '/Users/nicolai/Documents/GitHub/StreamDeck-Velocity/browser-extension'
            //   )
            //   .then((result) => {
            //     console.log('result', result);
            //   });
        });
        electron_1.app.whenReady().then(function () {
            if (isMac === true) {
                var isInApplicationsFolder = electron_1.app.isInApplicationsFolder();
                console.log('isInApplicationsFolder ' + isInApplicationsFolder);
                if (!isInApplicationsFolder) {
                    var userResponse = electron_1.dialog.showMessageBoxSync({
                        type: 'question',
                        buttons: ['Cancel', 'Move to Applications Folder'],
                        defaultId: 1,
                        title: 'Move to Applications Folder',
                        message: 'Do you want to move this app to the Applications folder?',
                        detail: 'This will ensure that the app is properly installed and can receive updates.',
                    });
                    if (userResponse === 1) {
                        electron_1.app.moveToApplicationsFolder({
                            conflictHandler: function (conflictType) {
                                if (conflictType === 'exists') {
                                    return (electron_1.dialog.showMessageBoxSync({
                                        type: 'question',
                                        buttons: ['Halt Move', 'Continue Move'],
                                        defaultId: 0,
                                        message: 'An app of this name already exists. Do you want to replace it?',
                                    }) === 1);
                                }
                            },
                        });
                    }
                }
            }
            // Add the extension to the session
            // const fqfp = path.join(__dirname, 'extension');
            if (getExtensionPref()) {
                console.log('Loading extension');
                var fqfp = path.join(__dirname.split('app.asar')[0], 'extension');
                console.log('fqfp', fqfp);
                electron_1.session.defaultSession
                    .loadExtension(fqfp, { allowFileAccess: true })
                    .then(function (_a) {
                    var id = _a.id;
                    console.log("Loaded extension: ".concat(id));
                });
            }
            // createWindow();
            // setTimeout(createWindow, 1000);
            setTimeout(createWindow, 200);
            // const icon = nativeImage.createFromPath(
            //   '../src/assets/icons/icon-48x48.png'
            // );
            // tray = new Tray(icon);
            // tray.setToolTip('Velocity Quick Menu');
            // tray.setTitle('Velocity');
        });
        // Quit when all windows are closed.
        electron_1.app.on('window-all-closed', function () {
            // On OS X it is common for applications and their menu bar
            // to stay active until the user quits explicitly with Cmd + Q
            // if (process.platform !== 'darwin') {
            //   app.quit();
            // }
            electron_1.app.quit();
        });
        electron_1.app.on('activate', function () {
            // On OS X it's common to re-create a window in the app when the
            // dock icon is clicked and there are no other windows open.
            if (mainWindow === null) {
                createWindow();
            }
        });
    }
}
catch (e) {
    console.error('Error in main.ts', e);
    throw e;
}
