const path = require('path');
const url = require('url');
const electron = require('electron')

const ipc = electron.ipcMain
const app = electron.app
const Menu = electron.Menu
const Tray = electron.Tray
const BrowserWindow = electron.BrowserWindow


let win

function createWindow () {
    win = new BrowserWindow({width: 500, height: 600, frame: false})
    win.isResizable(false)
    win.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
    }))

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

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

app.on('activate', () => {
    if (win === null) {
        createWindow()
    }
})

let appIcon = null

ipc.on('put-in-tray', function (event) {
    win.hide()
    const iconName = 'icons/icon.ico'
    const iconPath = path.join(__dirname, iconName)
    appIcon = new Tray(iconPath)
    const contextMenu = Menu.buildFromTemplate([{
        label: 'Show',
        click: function () {
            event.sender.send('tray-removed')
        }
    }, {
        label: 'Quit', 
        click: () => {
            app.quit()
        }
    }])

    appIcon.setToolTip('aMP3r')
    appIcon.setContextMenu(contextMenu)
})

ipc.on('remove-tray', function () {
    win.show()
    appIcon.destroy()
})

app.on('window-all-closed', function () {
    if (appIcon) appIcon.destroy()
})

ipc.on('quit' , (e) => {
    app.quit()
})