'use strict';

var chalk = require('chalk');
var co = require('co');
var request = require('request');
var inquirer = require('inquirer');
var childProcess = require('child_process');
var fs = require('fs');
var prompt = require('co-prompt');
var ora = require('ora');
require('babel-polyfill');

var openCmd = process.platform === 'win32' ? 'start' : 'open';
var spinner = ora({
  text: 'Loading Git notifications, can take a few seconds',
  color: 'yellow'
});

var notificationsURL = 'https://api.github.com/notifications';
var HOMEDIR = process.env[process.platform === 'WIN32' ? 'USERPROFILE' : 'HOME'];
var gitConfig = '.git-config';

function configExists() {
  if (!fs.existsSync(HOMEDIR + '/' + gitConfig)) {
    return false;
  }

  if (!fs.existsSync(HOMEDIR + '/' + gitConfig + '/config.json')) {
    return false;
  }

  return fs.readFileSync(HOMEDIR + '/' + gitConfig + '/config.json');
}

function saveConfig(params) {
  var userconfig = {
    username: params.username,
    password: params.password
  };

  if (!fs.existsSync(HOMEDIR + '/' + gitConfig)) {
    fs.mkdir(HOMEDIR + '/' + gitConfig);
    fs.writeFileSync(HOMEDIR + '/' + gitConfig + '/config.json', JSON.stringify(userconfig));
  } else {
    fs.writeFileSync(HOMEDIR + '/' + gitConfig + '/config.json', JSON.stringify(userconfig));
  }
}

function optGit() {
  co(regeneratorRuntime.mark(function _callee() {
    var username, password, userConfig, notificationsMap, notificationsArray, gitRequest;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (configExists()) {
              _context.next = 8;
              break;
            }

            _context.next = 3;
            return prompt('GitHub Username: ');

          case 3:
            username = _context.sent;
            _context.next = 6;
            return prompt.password('GitHub Password: ');

          case 6:
            password = _context.sent;

            saveConfig({ username: username, password: password });

          case 8:
            userConfig = JSON.parse(configExists());

            spinner.start();
            notificationsMap = {};
            notificationsArray = [];
            gitRequest = request.defaults({
              headers: {
                'User-Agent': 'ua'
              },
              auth: {
                username: userConfig.username,
                password: userConfig.password
              }
            });


            gitRequest(notificationsURL, function (err, resp, body) {
              if (err) {
                console.log(('Error: ' + err).red);
                process.exit(0);
              }

              var notifications = JSON.parse(body);

              spinner.stop();
              if (!notifications.length) {
                console.log(chalk.green('No new notifications'));
                process.exit();
              }

              for (var i = 0; i < notifications.length; i + 1) {
                var notification = notifications[i];
                notificationsArray.push(notification.subject.title);
                notificationsMap[notification.subject.title] = notification;
              }

              inquirer.prompt([{
                type: 'list',
                name: 'choice',
                message: 'Select notification...',
                choices: notificationsArray
              }]).then(function (answer) {
                var notification = notificationsMap[answer.choice];

                console.log(chalk.yellow('Type :') + '  ' + notification.subject.type);
                console.log(chalk.yellow('Repo :') + '  ' + notification.repository.name);
                console.log(chalk.yellow('Title :') + '  ' + notification.subject.title);
                console.log(chalk.yellow('URL :') + '  ' + notification.repository.url);

                inquirer.prompt([{
                  type: 'confirm',
                  name: 'Open',
                  message: 'Open in Browser?'
                }]).then(function (browser) {
                  if (browser.Open) {
                    setTimeout(function () {
                      childProcess.exec(openCmd + ' https://www.github.com/' + notification.repository.full_name + '/issues', function () {});
                    }, 300);
                  }
                });
              });
            });

          case 14:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, this);
  }));
}

module.exports = optGit;