const { app, ipcMain, protocol, session, BrowserWindow, BrowserView, Menu, nativeImage, clipboard, dialog, Notification } = require('electron');
const path = require('path');
const fs = require('fs');
const url = require('url');
const os = require('os');

const { autoUpdater } = require('electron-updater');

const { extensionsMain } = require('electron-extensions');
const config = require('./Config');

const WindowManager = require('./WindowManager');
const windowManager = new WindowManager();

const protocolStr = 'flast';
const fileProtocolStr = `${protocolStr}-file`;

let loginCallback;
let mainWindow;
let subWindow;

getBaseWindow = (width = 1100, height = 680, minWidth = 320, minHeight = 600, x, y, frame = false) => {
    return new BrowserWindow({
        width, height, minWidth, minHeight, x, y, 'titleBarStyle': 'hidden', frame, fullscreenable: true,
        webPreferences: {
            nodeIntegration: true,
            webviewTag: true,
            plugins: true,
            experimentalFeatures: true,
            contextIsolation: false,
        }
    });
}

module.exports = class Application {
    loadWindow = () => {
        protocol.registerSchemesAsPrivileged([
            { scheme: protocolStr, privileges: { standard: true, bypassCSP: true, secure: true } },
            { scheme: fileProtocolStr, privileges: { standard: false, bypassCSP: true, secure: true } }
        ]);

        autoUpdater.on('checking-for-update', () => {
            console.log('Checking for update...')
        })
        autoUpdater.on('update-available', (info) => {
            console.log('Update available.');
        })
        autoUpdater.on('update-not-available', (info) => {
            console.log('Update not available.');
        })
        autoUpdater.on('error', (err) => {
            console.log('Error in auto-updater. ' + err);
        })
        autoUpdater.on('download-progress', (progressObj) => {
            console.log('Download speed: ' + progressObj.bytesPerSecond + ' - Downloaded ' + progressObj.percent + '% (' + progressObj.transferred + "/" + progressObj.total + ')');
        })
        autoUpdater.on('update-downloaded', (info) => {
            console.log('Update downloaded.');
        });

        app.on('ready', () => {
            process.env.GOOGLE_API_KEY = config.googleAPIKey;

            session.defaultSession.setUserAgent(session.defaultSession.getUserAgent().replace(/ Electron\/[0-9\.]*/g, ''));

            autoUpdater.checkForUpdatesAndNotify();
            Menu.setApplicationMenu(null);

            windowManager.addWindow();
            // this.loadExtension('gmngpagflejjoblmmamaonmnkghjmebh');
            // this.loadExtension('bdiadchoogngocfifcomfeakccmcecee');
        });

        app.on('window-all-closed', () => {
            if (process.platform !== 'darwin') {
                app.quit();
            }
        });

        app.on('activate', () => {
        });

        app.on('login', (e, webContents, request, authInfo, callback) => {
            e.preventDefault();

            subWindow = getBaseWindow(320, 230, 320, 230);
            // subWindow.setParentWindow(mainWindow);
            subWindow.setMovable(false);
            subWindow.setResizable(false);
            subWindow.setMinimizable(false);
            subWindow.setMaximizable(false);
            const startUrl = process.env.ELECTRON_START_URL || url.format({
                pathname: path.join(__dirname, '/../build/index.html'),
                protocol: 'file:',
                slashes: true,
                hash: '/authentication',
            });

            subWindow.loadURL(startUrl);
            loginCallback = callback;
        });

        ipcMain.on('authorization', (event, arg) => {
            loginCallback(arg.username, arg.password);
            subWindow.close();
        });
    }

    loadExtension = (id) => {
        const extensionDir = path.resolve(os.homedir(), 'AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions');

        const versions = fs.readdirSync(`${extensionDir}/${id}`).sort();
        const version = versions.pop();

        // BrowserWindow.addExtension(`${extensionDir}/${id}/${version}`);
        // BrowserWindow.addDevToolsExtension(`${extensionDir}/${id}/${version}`);
        extensionsMain.setSession(session.defaultSession);
        extensionsMain.load(`${extensionDir}/${id}/${version}`);
    }
};