"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 });
// Modules to control application life and create native browser window
var electron_1 = require("electron");
var path = require("path");
var url = require("url");
var childProcess = require("child_process");
var fs = require("fs-extra");
var open_or_focus_app_1 = require("./open-or-focus-app");
var pkStorageFolderName = "PK_storage";
// this should be placed at top of main.js to handle setup events quickly
if (handleSquirrelEvent()) {
    // squirrel event handled and app will exit in 1000ms, so don't do anything else
}
function handleSquirrelEvent() {
    if (process.argv.length === 1) {
        return false;
    }
    var appFolder = path.resolve(process.execPath, '..');
    var rootAtomFolder = path.resolve(appFolder, '..');
    var updateDotExe = path.resolve(path.join(rootAtomFolder, 'Update.exe'));
    var exeName = path.basename(process.execPath);
    var spawn = function (command, args) {
        var spawnedProcess, error;
        try {
            spawnedProcess = childProcess.spawn(command, args, { detached: true });
        }
        catch (error) { }
        return spawnedProcess;
    };
    var spawnUpdate = function (args) {
        return spawn(updateDotExe, args);
    };
    var squirrelEvent = process.argv[1];
    switch (squirrelEvent) {
        case '--squirrel-install':
        case '--squirrel-updated':
            // Optionally do things such as:
            // - Add your .exe to the PATH
            // - Write to the registry for things like file associations and
            //   explorer context menus
            // Install desktop and start menu shortcuts
            spawnUpdate(['--createShortcut', exeName]);
            setTimeout(electron_1.app.quit, 1000);
            return true;
        case '--squirrel-uninstall':
            // Undo anything you did in the --squirrel-install and
            // --squirrel-updated handlers
            // Remove desktop and start menu shortcuts
            spawnUpdate(['--removeShortcut', exeName]);
            setTimeout(electron_1.app.quit, 1000);
            return true;
        case '--squirrel-obsolete':
            // This is called on the outgoing version of your app before
            // we update to the new version - it's the opposite of
            // --squirrel-updated
            electron_1.app.quit();
            return true;
    }
}
;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow;
var childWindow;
var quicknotewindow;
function createWindow() {
    var electronScreen = electron_1.screen;
    var size = electronScreen.getPrimaryDisplay().workAreaSize;
    mainWindow = new electron_1.BrowserWindow({
        x: 0, y: 0, width: size.width,
        height: size.height, parent: mainWindow,
        icon: path.join(__dirname, 'assets', 'icon', 'win_icon.ico'),
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            sandbox: false
        }
    });
    // and load the index.html of the app.
    //mainWindow.loadFile('build/index.html')
    // Load a URL in the window to the local index.html path
    var urlFormat = {
        pathname: path.join(__dirname, 'build/index.html'),
        protocol: 'file:',
        slashes: true
    };
    mainWindow.loadURL(url.format(urlFormat));
    electron_1.protocol.registerHttpProtocol('loehnapplication', function (request) {
        if (childWindow) {
            if (request.url.indexOf('loehnapplication://auth365') !== -1) {
                mainWindow.webContents.send('officeauth', { msg: request.url });
                childWindow.close();
            }
            else {
                childWindow.close();
                mainWindow.loadURL(url.format(urlFormat));
            }
            childWindow = null;
        }
    });
    // Open the DevTools.
    //mainWindow.webContents.openDevTools()
    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });
    var template = [
        {
            label: 'Edit',
            submenu: [
                { role: 'undo' },
                { role: 'redo' },
                { type: 'separator' },
                { role: 'cut' },
                { role: 'copy' },
                { role: 'paste' },
                // { role: 'pasteandmatchstyle' },
                { role: 'delete' },
                // { role: 'selectall' }
            ]
        },
        {
            label: electron_1.app.getName(), submenu: [
                {
                    label: 'Reload', accelerator: 'CmdOrCtrl+R',
                    click: function (item, focusedWindow) {
                        // Electron 40: focusedWindow is now BaseWindow, cast to BrowserWindow for loadURL
                        if (focusedWindow)
                            focusedWindow.loadURL(url.format(urlFormat));
                    }
                },
                {
                    label: 'Toggle Developer Tools',
                    accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
                    click: function (item, focusedWindow) {
                        // Electron 40: focusedWindow is now BaseWindow, cast to BrowserWindow for webContents
                        if (focusedWindow)
                            focusedWindow.webContents.toggleDevTools();
                    }
                },
                { type: 'separator' },
                { role: 'quit' }
            ]
        }
    ];
    var menu = electron_1.Menu.buildFromTemplate(template);
    electron_1.Menu.setApplicationMenu(menu);
    electron_1.session.defaultSession.webRequest.onBeforeSendHeaders({
        urls: ['https://graph.microsoft.com/*']
    }, function (details, callback) {
        delete details.requestHeaders['User-Agent'];
        details.requestHeaders['Host'] = 'localhost';
        callback({ requestHeaders: details.requestHeaders });
    });
}
// 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.
// protocol.registerStandardSchemes(['loehnapplication']);
electron_1.protocol.registerSchemesAsPrivileged([
    { scheme: 'loehnapplication', privileges: { standard: true } }
]);
electron_1.app.on('ready', createWindow);
// 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') {
        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();
    }
});
/* handle IPC events here */
// open storage (PK => Ablage)
electron_1.ipcMain.on('openStorage', function (event, folder, companyPrefix, projectNumber, companyspecific, standard) {
    if (companyspecific === void 0) { companyspecific = false; }
    if (standard === void 0) { standard = false; }
    if (projectNumber) {
        if (!companyPrefix) {
            companyPrefix = standard ? "P" : "";
        }
        var pkStorageFolderPath = folder || path.join(electron_1.app.getPath('userData'), pkStorageFolderName);
        var pkCompanyStorageFolderPath = void 0;
        if (!companyspecific) {
            pkCompanyStorageFolderPath = path.join(pkStorageFolderPath, companyPrefix);
        }
        else {
            pkCompanyStorageFolderPath = pkStorageFolderPath;
        }
        var projectStorageFolderPath = path.join(pkCompanyStorageFolderPath, String(projectNumber));
        if (!fs.existsSync(pkStorageFolderPath)) {
            fs.mkdirSync(pkStorageFolderPath);
        }
        if (!fs.existsSync(pkCompanyStorageFolderPath)) {
            fs.mkdirSync(pkCompanyStorageFolderPath);
        }
        if (!fs.existsSync(projectStorageFolderPath)) {
            fs.mkdirSync(projectStorageFolderPath);
        }
        electron_1.shell.openPath(projectStorageFolderPath);
    }
});
electron_1.ipcMain.on('openIndividualStorage', function (event, folder, isUrl) {
    if (fs.existsSync(folder) || isUrl) {
        electron_1.shell.openPath(folder);
    }
});
electron_1.ipcMain.on('openNotizapp', function (event, folder, isUrl) {
    (0, open_or_focus_app_1.openOrFocus)(folder, isUrl).catch(function (error) {
        console.error('Failed to open or focus:', error);
    });
});
// open routines
electron_1.ipcMain.on('openRoutines', function (event, folder) {
    var pkStorageFolderPath = folder || path.join(electron_1.app.getPath('userData'), pkStorageFolderName);
    if (!fs.existsSync(pkStorageFolderPath)) {
        fs.mkdirSync(pkStorageFolderPath);
    }
    electron_1.shell.openPath(pkStorageFolderPath);
});
electron_1.ipcMain.on('getLocalStorage', function (event) {
    event.sender.send('getLocalStorageReply', path.join(electron_1.app.getPath('userData'), pkStorageFolderName));
});
// Print function
electron_1.ipcMain.on('printPage', function (event, file) {
    saveBuffer(file, "export".concat(new Date().getTime(), ".pdf"), function (localPath, err) {
        if (err) {
            console.log('An error ocurred creating the file' + err.message);
        }
        else {
            electron_1.shell.openPath(localPath);
            /*
            const PDFWindow = require('electron-pdf-window');
            const win = new BrowserWindow({ width: 800, height: 600, show: false })
      
            PDFWindow.addSupport(win);
            win.loadURL(localPath);
            win.webContents.on('did-finish-load', () => {
              function print() {
                let code = "var button = document.getElementById('print'); button.click()";
                win.webContents.executeJavaScript(code);
              }
              setTimeout(print, 1000);
            });
            */
        }
    });
});
function saveBuffer(buffer, fileName, callback) {
    var pkStorageFolderPath = path.join(electron_1.app.getPath('userData'), pkStorageFolderName);
    if (!fs.existsSync(pkStorageFolderPath)) {
        fs.mkdirSync(pkStorageFolderPath);
    }
    var localPath = pkStorageFolderPath + '/' + fileName;
    fs.writeFile(localPath, buffer, function (err) {
        callback(localPath, err);
    });
    /*fs.outputFile(fileName, buffer, err => {
      callback(fileName, err);
    });*/
}
//Store PDF File on disk
function storePdfFile(file, callback) {
    var pkStorageFolderPath = path.join(electron_1.app.getPath('userData'), pkStorageFolderName);
    if (!fs.existsSync(pkStorageFolderPath)) {
        fs.mkdirSync(pkStorageFolderPath);
    }
    var localPath = pkStorageFolderPath + "/export".concat(new Date().getTime(), ".pdf");
    fs.writeFile(localPath, file, function (err) {
        callback(localPath, err);
    });
}
//Open child window
electron_1.ipcMain.on('openChildWindow', function (event, url) {
    childWindow = new electron_1.BrowserWindow({ parent: mainWindow, modal: true, show: false });
    childWindow.on('closed', function (event, url) {
        mainWindow.webContents.send('officeauth', { msg: 'error_subcode=cancel' });
        childWindow = null;
    });
    childWindow.loadURL(url);
    childWindow.once('ready-to-show', function () {
        childWindow.show();
    });
});
// select storage directory
electron_1.ipcMain.on('getStorageDirectory', function (event, data) { return __awaiter(void 0, void 0, void 0, function () {
    var selectedfolder, err_1;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                _a.trys.push([0, 2, , 3]);
                return [4 /*yield*/, electron_1.dialog.showOpenDialog(mainWindow, { properties: ['openDirectory'] })];
            case 1:
                selectedfolder = _a.sent();
                event.sender.send('getStorageDirectoryReply', [data, selectedfolder.filePaths]);
                return [3 /*break*/, 3];
            case 2:
                err_1 = _a.sent();
                console.error('Failed to open dialog:', err_1);
                event.sender.send('getStorageDirectoryReply', [data, []]);
                return [3 /*break*/, 3];
            case 3: return [2 /*return*/];
        }
    });
}); });
// Handle Angular button click
electron_1.ipcMain.handle('open-quicknotes-window', function () { return __awaiter(void 0, void 0, void 0, function () {
    return __generator(this, function (_a) {
        return [2 /*return*/, openQuicknotes()];
    });
}); });
var quicknotesFilePath = path.join(electron_1.app.getPath('userData'), 'quicknotes.txt');
function openQuicknotes() {
    return new Promise(function (resolve) {
        if (quicknotewindow) {
            quicknotewindow.focus();
            return resolve(null);
        }
        quicknotewindow = new electron_1.BrowserWindow({
            width: 800,
            height: 600,
            parent: mainWindow,
            title: 'Schnellnotiz',
            modal: process.platform === 'darwin' ? false : true,
            frame: true,
            titleBarStyle: 'default',
            autoHideMenuBar: false,
            webPreferences: {
                nodeIntegration: true,
                contextIsolation: false,
            },
        });
        // Load HTML content directly (programmatically)
        var notesAvailable = fs.existsSync(quicknotesFilePath)
            ? fs.readFileSync(quicknotesFilePath, 'utf-8')
            : '';
        var html = "\n      <!DOCTYPE html>\n      <html>\n      <head>\n  <style>\n    html, body {\n      margin: 0;\n      padding: 0;\n      height: 100%;\n      width: 100%;\n      overflow: hidden; /* prevent body scroll */\n    }\n    textarea {\n      background-color: #ffffd8;\n      color: #000;\n      width: 100%;\n      height: 100%;\n      box-sizing: border-box; \n      resize: none;          \n      padding: 8px;\n      font-size: 20px;\n      font-family: \"Segoe UI\", Arial, sans-serif;\n      overflow: auto;         /* enables scrollbar when content overflows */\n      border: 2px solid #c7e3ff;\n      outline: none;\n    }\n    textarea:focus {\n      border-color: #b7dcff;\n      box-shadow: 0 0 0 2px #d9ecff;\n      outline: none;\n    }\n  </style>\n</head>\n<body>\n<textarea id=\"notice\">".concat(notesAvailable, "</textarea>\n        <script>\n          const { ipcRenderer } = require('electron');\n          const textarea = document.getElementById('notice');\n\n          // Auto-save every 5 seconds\n          const autoSaveInterval = setInterval(() => {\n            ipcRenderer.send('save-quicknotes', textarea.value);\n          }, 5000);\n\n          // Save on close\n          window.addEventListener('beforeunload', () => {\n            clearInterval(autoSaveInterval);\n            ipcRenderer.send('save-quicknotes', textarea.value);\n          });\n        </script>\n      </body>\n      </html>\n    ");
        quicknotewindow.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(html));
        // Listen for content saves
        electron_1.ipcMain.on('save-quicknotes', function (event, content) {
            fs.writeFileSync(quicknotesFilePath, content, 'utf-8');
        });
        quicknotewindow.on('closed', function () {
            quicknotewindow = null;
            resolve(fs.existsSync(quicknotesFilePath) ? quicknotesFilePath : null);
            electron_1.ipcMain.removeAllListeners('save-quicknotes');
        });
    });
}
