path = require('path')
fs = require ('fs')

app = require('app')
Menu = require('menu')
Tray = require('tray')
dialog = require('dialog')
BrowserWindow = require('browser-window')
spawn = require('child_process').spawn
mainWindow = null
vipEmail = ''
server = null
port = 8000
serverStarted = false

FOLDERS =
    HTML: path.join(__dirname, 'html')
    BACKUP: path.join(__dirname, 'backup')
    UTILS: path.join(__dirname, 'utils')
    IMG: path.join(__dirname, 'img')

startServer = (cb)->
    switch process.platform
        when 'darwin'
            serverPath = path.join(FOLDERS.UTILS, 'server')
        when 'win32'
            serverPath = path.join(FOLDERS.UTILS, 'server.exe')
        when 'linux'
            serverPath = path.join(FOLDERS.UTILS, 'server-linux')
        else
            return
    server = spawn serverPath, [port]
    doTimeout = null
    server.stdout.on 'data', (data) ->
        console.log '----stdout: ' + data
        return

    server.stderr.on 'data', (data) ->
        console.log '----stderr: ' + data
        if not serverStarted
            port++
            clearTimeout doTimeout if doTimeout
            startServer cb
        return

    clearTimeout doTimeout if doTimeout
    doTimeout = setTimeout (->
        serverStarted = true
        cb()
    ), 1000

redirect = (url)->
    mainWindow.loadUrl('file://' + path.join(FOLDERS.HTML, url))

cleanBackup = ->
    for file in fs.readdirSync(FOLDERS.BACKUP)
        fullPath = path.join(FOLDERS.BACKUP, file)
        fs.unlinkSync fullPath
        console.log '[Main cleanBackup delete]', file

showOpenDialog = (cb)->
    options =
        properties: ['openFile', 'openDirectory', 'multiSelections']
        filters: [
            {
                name: 'Images'
                extensions: ['png', 'jpeg', 'jpg']
            }
        ]

    dialog.showOpenDialog mainWindow, options, (fullPathList)->
        console.log '[Main showOpenDialog] fullPathList', fullPathList
        cb(fullPathList) if cb and fullPathList


global['redirect'] = redirect
global['FOLDERS'] = FOLDERS
global['showOpenDialog'] = showOpenDialog
global['getEmail'] = -> return vipEmail
global['setEmail'] = (email)-> vipEmail = email
global['openExternal'] = require('shell').openExternal
global['openDevTools'] = ->
    mainWindow.openDevTools()
global['port'] = -> return port


app.on 'window-all-closed', ->
    server.kill()
    app.quit()

app.on 'ready', ->
    mainWindow = new BrowserWindow {width: 1280, height: 768, 'min-width': 800, 'min-height': 680, frame: true, show: false}
    #    mainWindow.setPosition 50,50
    fs.mkdir(FOLDERS.BACKUP) if not fs.existsSync(FOLDERS.BACKUP)
    cleanBackup()
    startServer ->
        redirect('layout.html')
        setTimeout (-> mainWindow.show()), 2000

    mainWindow.on 'closed', ->
        mainWindow = null
        cleanBackup()
 




