const path = require('path');
const spawn = require('child_process').spawn;
const http = require('http');

const BrowserWindow = require('browser-window');
const ipcMain = require('electron').ipcMain;
const app = require('app');
const Menu = require('menu');

const commons = require('./commons.js');

const MAIN_PAGE_URL = `file://${path.join(__dirname, "../app/main.html")}`;
const DIFF_PAGE_URL = `file://${path.join(__dirname, "../app/diff.html")}`;
const ABOUT_PAGE_URL = `file://${path.join(__dirname, "../app/about.html")}`;

var mainWindow = null;
var diffWindow = null;
var aboutWindow = null;

var server = null;
var port = 8911;
var serverConnected = false;

var closing = false;

global['port'] = ()=> port;


function mustStartServer() {
    var binDir = commons.isDebug() ? `../bin/${process.platform}` : "../bin";
    const joinBinFolder = (dir)=> path.join(path.join(__dirname, binDir), dir);
    const binName = {
        darwin: 'server',
        win32: 'server.exe'
    };
    var serverPath = joinBinFolder(binName[process.platform]);
    server = spawn(serverPath, [`--port=${port}`, `--binDir=${joinBinFolder('/')}`, `--cacheDir=${commons.CACHE_DIR}`, `--db=${commons.DB_PATH}`]);
    server.stdout.on('data', (data)=> {
        return console.log('----stdout: ' + data)
    });
    server.stderr.on('data', (data)=> {
        console.log('----stderr: ' + data);
        if (!serverConnected) {
            port++;
            mustStartServer()
        }
    });
}

function setupMenu() {
    if (commons.isDebug()) return;
    if (process.platform == 'darwin') {
        var template = [
            {
                label: "PP鸭",
                submenu: [
                    {label: "退出", accelerator: "Command+Q", click: () => app.quit()}
                ]
            },
            {
                label: "编辑",
                submenu: [
                    {label: "撤销", accelerator: "CmdOrCtrl+z", selector: "undo:"},
                    {label: "重做", accelerator: "CmdOrCtrl+r", selector: "redo:"},
                    {type: "separator"},
                    {label: "剪切", accelerator: "CmdOrCtrl+x", selector: "cut:"},
                    {label: "复制", accelerator: "CmdOrCtrl+c", selector: "copy:"},
                    {label: "粘贴", accelerator: "CmdOrCtrl+v", selector: "paste:"},
                    {label: "全选", accelerator: "CmdOrCtrl+a", selector: "selectAll:"}
                ]
            }
        ];
        Menu.setApplicationMenu(Menu.buildFromTemplate(template));
    }
}


function main() {
    app.commandLine.appendSwitch('no-proxy-server');

    app.on('quit', ()=> {
        if (server) server.kill();
    });

    app.on('ready', ()=> {
        mainWindow = new BrowserWindow({width: 400, height: 560, 'min-width': 400, 'min-height': 500, show: false});
        mainWindow.on('close', ()=> {
            mainWindow.webContents.session.clearCache(()=> {
                console.log('clear cache done');
            });
        });

        const openMain = ()=> {
            mainWindow.loadURL(MAIN_PAGE_URL);
            mainWindow.webContents.on('did-finish-load', ()=>mainWindow.show());

            mainWindow.on('closed', (e) => {
                closing = true;
                diffWindow.close();
                aboutWindow.close();
                app.quit();
            })
        };


        diffWindow = new BrowserWindow({width: 800, height: 600, 'min-width': 400, 'min-height': 400, show: false});
        diffWindow.loadURL(DIFF_PAGE_URL);
        diffWindow.on('close', (e) => {
            if (closing) return;
            e.preventDefault();
            diffWindow.hide();
        });

        aboutWindow = new BrowserWindow({width: 300, height: 390, resizable: false, show: false});
        aboutWindow.loadURL(ABOUT_PAGE_URL);
        aboutWindow.on('close', (e)=> {
            if (closing) return;
            e.preventDefault();
            aboutWindow.hide()
        });
        aboutWindow.webContents.on('did-finish-load', ()=> {
            aboutWindow.webContents.send('VERSION', app.getVersion());
        });

        const mustGetServerInfo = ()=> {
            http.get(`http://127.0.0.1:${port}/info`, (res)=> {
                if (res.statusCode == 200) {
                    console.log('===', port);
                    serverConnected = true;
                    openMain();
                } else {
                    console.log('==! ', res.statusCode, port);
                    return setTimeout(mustGetServerInfo, 100);
                }

            }).on('error', (e)=> {
                console.log('xxx', port);
                return setTimeout(mustGetServerInfo, 100);
            });
        };
        mustGetServerInfo();
        if (!commons.isDebug() || true) {
            mustStartServer();
        }

        setupMenu();
    });

    ipcMain.on('FOCUS_MAIN', ()=> {
        mainWindow.focus();
    });

    ipcMain.on('OPEN_DEV_TOOLS', ()=> {
        var openDevTools = (windowToOpen) => windowToOpen ? windowToOpen.webContents.openDevTools({'detach': true}) : "";
        [mainWindow, aboutWindow, diffWindow].map(openDevTools)
    });
    ipcMain.on('NEW_DIFF_FILE', (e, file)=> {
        diffWindow.webContents.send('NEW_DIFF_FILE', file);
    });

    ipcMain.on('OPEN_DIFF', ()=> {
        diffWindow.show();
        diffWindow.focus();
    });

    ipcMain.on('OPEN_ABOUT', ()=> {
        aboutWindow.show();
    });

    ipcMain.on('OPEN_CHANGE_ACTIVATION', ()=> {
        mainWindow.webContents.send('OPEN_CHANGE_ACTIVATION_MODAL');
        mainWindow.focus();
    });

    ipcMain.on('RESTORE_FILE', ()=> {
        mainWindow.webContents.send('RESTORE_FILE');
    });

    ipcMain.on('RECOMPRESS_FILE', ()=> {
        mainWindow.webContents.send('RECOMPRESS_FILE');
    });

    ipcMain.on('ABOUT_ACTIVATED', (e, activated)=> {
        aboutWindow.webContents.send('ABOUT_ACTIVATED', activated);
    })
}

module.exports = main;