app = require "app"
path = require "path"
os = require "os"
env = require("./env")
fs = require "fs"
net = require 'net'
config =  require("./config") #JSON.parse(fs.readFileSync("./config.json"));
locale = require("./locales/" + config.language) #JSON.parse(fs.readFileSync("./locales/" + config.language + ".json"));
(require "crash-reporter").start()

global.mx_config = config

DefaultSocketPath =
  if process.platform is 'win32'
    '\\\\.\\pipe\\marxico-sock'
  else
    path.join(os.tmpdir(), "marxico-#{process.env.USER}.sock")


socketPath = DefaultSocketPath

app.on "window-all-closed",()->
    # default behavior in darwin is
    #    if process.platform != "darwin"
    app.quit()

app.on "open-file",(event, path)->
    console.log "open-file", path

app.on "will-quit", ()->
    deleteSocketFile()

app.on "will-exit", ()->
    deleteSocketFile()

base_url = locale.index
env.base_url = base_url
to_open_url = ''
app.on "open-url",(event, url)->
    console.log "open-url", url
    to_open_url = url
    
    if env.window
        open_window to_open_url

if /guid/.test(process.argv[1])
	to_open_url = process.argv[1]


open_window = (to_open_url) -> 
    BrowserWindow = require "browser-window"

    settings = {
        width: 800
        height: 600
        center: true
        frame: false
        "web-preferences" : {
            "web-security" : false
        }
    }
    window = new BrowserWindow settings
    _url = base_url;

    if to_open_url
        url = require 'url'
        p2 = url.parse to_open_url
        p1 = url.parse base_url
        p1.hash = p2.hash
        p1.search = p2.search
        _url = url.format p1


    window.loadUrl _url
    env.window = window
    env.window_settings = settings
   
deleteSocketFile = ()->
   return if process.platform is 'win32'

    if fs.existsSync(socketPath)
      try
        fs.unlinkSync(socketPath)
      catch error
        # Ignore ENOENT errors in case the file was deleted between the exists
        # check and the call to unlink sync. This occurred occasionally on CI
        # which is why this check is here.
        # throw error unless error.code is 'ENOENT'

createApplication = () -> 
    require "./menu"
    open_window to_open_url

    deleteSocketFile()
    server = net.createServer (connection) =>
      connection.on 'data', (data) =>
        console.log "server data", data
        open_window JSON.parse(data).to_open_url

    server.listen socketPath
    server.on 'error', (error) -> console.error 'Application server failed', error

app.on "ready",()->
    if (process.platform isnt 'win32' and not fs.existsSync socketPath)
        createApplication()  
        return 

    client = net.connect {path: socketPath}, ->
        console.log "socket exist"
        client.write JSON.stringify({ to_open_url: to_open_url }), ->
        client.end()
        app.terminate()

    client.on 'error',  createApplication


