import { app, ipcMain, nativeImage, BrowserWindow, Menu, Tray } from 'electron'
import FileSystem from 'fs'
import Autolaunch from 'auto-launch'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
import { enableLiveReload } from 'electron-compile'
import { readSettings, writeSettings } from './settings'
import { createServer, restartServer } from './server'

let win
let tray
let settings = readSettings()

// const isDevMode = process.execPath.match(/[\\/]electron/)
const isDevMode = settings.appMode === 'development'

const AppAutolaunch = new Autolaunch({
    name: 'Servidor de Impresión',
    isHidden: true
})

if (isDevMode) {
    enableLiveReload()
}

const isSecondInstance = app.makeSingleInstance(() => {
    if (win) {
        if (win.isMinimized()) {
            win.restore()
            win.focus()
        }
    }
})

if (isSecondInstance) {
    app.quit()
}

/**
 * 
 */
const createWindow = async () => {
    if (win) {
        win.show()
        return
    }

    win = new BrowserWindow({
        title: settings.appName,
        titleBarStyle: 'hidden',
        width: 350,
        height: 480,
        maximizable: isDevMode,
        resizable: isDevMode,
        center: true,
        show: false
    })
    
    win.setMenuBarVisibility(false)
    win.loadURL(`file://${__dirname}/index.html`)    

    if (isDevMode) {
        await installExtension(VUEJS_DEVTOOLS)
        win.webContents.openDevTools()

        AppAutolaunch.disable()
    } else {
        AppAutolaunch.enable()
    }

    AppAutolaunch.isEnabled().then(enable => {
        if (enable) {
            return
        }

        if (isDevMode) {
            AppAutolaunch.disable()
        } else {
            AppAutolaunch.enable()
        }
    }).catch(e => {
        console.log(e)
    })

    win.once('ready-to-show', () => {
        win.show()
    })

    win.on('show', () => {
        tray.setHighlightMode('always')
    })

    win.on('hide', () => {
        tray.setHighlightMode('never')
    })

    win.on('close', e => {
        e.preventDefault()
        win.hide()
    })

    win.on('closed', () => {
        win = null
    })
}

/**
 * 
 */
const exitApp = async () => {
    if (process.platform !== 'darwin') {
        app.exit()
    }
}

/**
 * Create system tray app
 */
const createTray = async () => {
    let icon = `${__dirname}/printer.png`

    if (!FileSystem.existsSync(icon)) {
        icon = nativeImage.createEmpty()
    }

    tray = new Tray(icon)
    tray.setToolTip(settings.appName)

    const contextMenu = Menu.buildFromTemplate([
        {
            label: 'Configuración',
            click: () => createWindow()
        },
        {
            label: 'Salir',
            click: () => exitApp()
        }
    ])

    tray.setContextMenu(contextMenu)
}

app.on('ready', async () => {
    await createTray()
    await createServer()
});

ipcMain.on('read-data', e => {
    settings = readSettings()
    e.returnValue = {
        port: settings.server.port,
        alwaysPdf: settings.print.alwaysPdf
    }
})

ipcMain.on('save-data', (e, data) => {
    settings.server.port = data.port
    settings.print.alwaysPdf = data.alwaysPdf

    writeSettings(settings)
    
    e.returnValue = data
})

ipcMain.on('restart-server', async e => {
    await restartServer()
    e.sender.send('server-restarted')
})
