'use strict';

var app = require('app')
  , BrowserWindow = require('browser-window')
  , Tray = require('tray')
  , Menu = require('menu')
  , MenuItem = require('menu-item')
  , clipboard = require('clipboard')
  , nativeImage = require('native-image')
  , path = require('path')
  , shell = require('shell')
  , platform = {
    Windows: /^win/i.test(process.platform),
    OSX: /^darwin/i.test(process.platform),
    Linux: /unix/i.test(process.platform)
  }
  , globalShortcut = require('global-shortcut')

var UpdateManager = require('./update-manager')
  , LocalConfig = require('./localconfig')
  , json = require('./package.json')

var config = null
  , screenshot = null
  , mainWindow = null
  , tray = null
  , updateManager = null
  , isManualClose = false

function setMenu () {
  if (platform.OSX) require('./menu');
}

function setTrayUnread () {
  tray.setImage(path.join(__dirname, 'macicon_newTemplate.png'));
}

function setTrayRead () {
  tray.setImage(path.join(__dirname, 'maciconTemplate.png'));
}

/**
 * Pubu service
 */
var PubuIM = {
  setBadge: function (badge) {
    if (!platform.OSX) return;

    app.dock.setBadge(badge ? badge + '' : '');

    if (badge) setTrayUnread();
    else setTrayRead();
  },
  takeScreenshot: function () {
    if (!screenshot) return;
    screenshot(function (err, buff) {
      if (err || !buff) return;
      clipboard.writeImage(nativeImage.createFromBuffer(buff), "image/png");
      mainWindow.show();
      mainWindow.webContents.send('slave', 'screenshot');
    })
  }
};

/**
 * Some loading functions
 */
function setMainWindow () {
  var windowConfig = {width: config.width || 1024, height: config.height || 768, title: json.appname};
  if (config.x) windowConfig.x = config.x;
  if (config.y) windowConfig.y = config.y;
  mainWindow = new BrowserWindow(windowConfig);
  isManualClose = false;

  /**
   * Handle Pubu.IM events
   */
  mainWindow.on('master', function (name, args) {
    if (!PubuIM[name]) return;

    PubuIM[name].apply(null, args || []);
  });

  mainWindow.loadUrl("file://" + path.join(__dirname, 'index.html'));
  // mainWindow.openDevTools({detach: true});

  mainWindow.webContents.on('new-window', function (event, url, name) {
    if (!/^pubu_/.test(name)) {
      event.preventDefault();
      shell.openExternal(url);
    }
  });

  mainWindow.webContents.on('dom-ready', function () {
    // Note: Call updateManager.check() to check update.
    //       Call updateManager.install() to quit app and install update.
    if (updateManager || /^win/i.test(process.platform)) return;
    updateManager = new UpdateManager(app.getVersion());

    // Show dialog to install
    updateManager.on('update-downloaded', function (releaseInfo) {
      var dialog = require('dialog');
      var ret = dialog.showMessageBox(mainWindow, {
        type: 'info',
        buttons: ['取消', '安装并重启'],
        icon: path.join(__dirname, 'macicon.png'),
        message: '发现更新：' + releaseInfo.releaseVersion,
        title: '应用更新',
        detail: releaseInfo.releaseNotes
      });
      if (ret === 1) {
        isManualClose = true;
        updateManager.install();
      }
    });
  });

  mainWindow.on('close', function (event) {
    if (isManualClose) return;
    event.preventDefault();
    mainWindow.hide();
  });

  mainWindow.on('closed', function () {
    mainWindow = null;
  });

  mainWindow.on('resize', function () {
    config = mainWindow.getBounds();
    LocalConfig.set(config);
  });

  mainWindow.on('move', function () {
    config = mainWindow.getBounds();
    LocalConfig.set(config);
  });
}

function setTray () {
  var icon;
  if (!platform.OSX) {
    icon = 'winicon.png';
  } else {
    icon = 'maciconTemplate.png';
  }

  tray = new Tray(path.join(__dirname, icon));
  tray.setToolTip('瀑布IM');
  tray.on('clicked', function () {
    if (!mainWindow) setMainWindow();
    mainWindow.show();
    mainWindow.webContents.send('slave', 'trayActive');
  })

  if (platform.Windows) {
    var menu = new Menu();
    menu.append(new MenuItem({
      label: "显示瀑布IM",
      click: function () {
        if (!mainWindow) setMainWindow();
        mainWindow.show();
        mainWindow.webContents.send('slave', 'trayActive');
      }
    }))

    menu.append(new MenuItem({
      label: "退出",
      click: function () {
        isManualClose = true;
        app.quit();
      }
    }))

    tray.setContextMenu(menu)
  }
}

// Only support Windows and OSX
if (platform.Windows || platform.OSX) {
  screenshot = require('screenshot')
}

/**
 * Set global variables for render process
 */
global.__dirname = __dirname;

// Report crashes to our server.
require('crash-reporter').start({
  productName: 'PubuIM',
  companyName: 'Pubu, LLC',
  submitUrl: `${json.pubuim.reportUrl}/post`,
  autoSubmit: true
});


/**
 * Quit app
 */
app.on('before-quit', function () {
  isManualClose = true;
});

/**
 * Quit when all closed
 */
app.on('window-all-closed', function () {
  app.quit();
});

/**
 * Handle with no open windows
 */
app.on('activate-with-no-open-windows', function () {
  if (!mainWindow) setMainWindow();
  mainWindow.show();
});

/**
 * Handle app ready
 */
app.on('ready', function () {
  LocalConfig.get(function (err, json) {
    console.log('Get config', err, json);

    config = json || {};
    setMainWindow();
    mainWindow.show();

    config = mainWindow.getBounds();
    LocalConfig.set(config);
  });

  setTray();
  setMenu();

  // Register global shortcut
  if (platform.OSX) {
    globalShortcut.register('ctrl+cmd+s', function () {
      PubuIM.takeScreenshot();
    });
  } else if (platform.Windows) {
    globalShortcut.register('ctrl+alt+s', function () {
      PubuIM.takeScreenshot();
    });
  }
});

app.on('menu.screenshot', function () {
  PubuIM.takeScreenshot();
});

app.on('menu.checkUpdate', function () {
  if (!updateManager || updateManager.state !== 'idle' && updateManager.state !== 'no-update-available') return;
  updateManager.check();
});

app.on('menu.reload', function () {
  BrowserWindow.getFocusedWindow().reloadIgnoringCache();
});

app.on('menu.help', function () {
  if (!mainWindow) return;
  mainWindow.show();
  mainWindow.webContents.send('slave', 'showHelp');
});

app.on('menu.homepage', function () {
  shell.openExternal('https://pubu.im');
});
