'use babel';

import GitHubApi from 'github';
import Shell from 'shell';

const github = new GitHubApi({
  version: '3.0.0',
  host: 'api.github.com'
});

function getGitHubCredentials() {
  let {githubUsername, githubAuthorizationToken} = atom.config.get('github-utils');

  if (githubUsername === '' || githubAuthorizationToken === '') {
    githubUsername = process.env.GITHUB_USERNAME;
    githubAuthorizationToken = process.env.GITHUB_ACCESS_TOKEN;
  }

  if (typeof githubAuthorizationToken === 'undefined' || typeof githubAuthorizationToken === 'undefined') {
    atom.notifications.addError('In order to view pull requests, you must configure your GitHub API credentials!');
    return null;
  }

  return [githubUsername, githubAuthorizationToken];
}

function authenticate () {
  const creds = getGitHubCredentials();

  if (creds === null) {
    return false;
  }
  const [githubUsername, githubAuthorizationToken] = creds;

  github.authenticate({
    type: 'basic',
    username: githubUsername,
    password: githubAuthorizationToken
  });

  return true;
}

function getRepositories () {
  return Promise.all(atom.project.getDirectories().map(atom.project.repositoryForDirectory.bind(atom.project)));
}

function parseRepositoryInfoFromURL (url) {
  const matched = url.match(/github\.com[:\/](.*?)(\.git)?$/);
  return matched ? matched[1].split('/') : null;
}

function getPullRequestURLs (pullRequests, branch) {
  return pullRequests.filter(pr => pr.head.ref === branch).map(pr => pr.html_url);
}

function viewPullRequests () {
  const authenticated = authenticate();

  if (!authenticated) {
    return;
  }

  getRepositories().then((repos) => {
    repos.forEach((repo) => {
      const remotes = [repo.getConfigValue('remote.origin.url')];
      const upstreamRemote = repo.getConfigValue('remote.upstream.url');
      if (upstreamRemote) {
        remotes.push(upstreamRemote);
      }
      remotes.forEach((remoteUrl) => {
        const repoInfo = parseRepositoryInfoFromURL(remoteUrl);
        if (!repoInfo) {
          return;
        }

        const [repoOwner, repoName] = repoInfo;
        if (!(repoOwner && repoName)) {
          return;
        }

        const branch = repo.getShortHead();
        github.pullRequests.getAll({
          user: repoOwner,
          repo: repoName,
          state: atom.config.get('github-utils.viewClosedPullRequests') ? 'all' : 'open'
        }, (err, pullRequests) => {
          if (err) {
            return console.error(err);
          }
          getPullRequestURLs(pullRequests, branch).forEach(Shell.openExternal);
        });
      })

    });
  });
}

export default {
  config: {
    githubUsername: {
      title: 'GitHub username',
      type: 'string',
      default: '',
      order: 0
    },
    githubAuthorizationToken: {
      title: 'GitHub authorization token',
      type: 'string',
      default: '',
      order: 1
    },
    viewClosedPullRequests: {
      title: 'View closed pull requests',
      description: 'Check to also view closed pull requests',
      type: 'boolean',
      default: false,
      order: 3
    }
  },

  activate() {
    atom.commands.add('atom-workspace', 'github-utils:view-pull-request', viewPullRequests);
  },
  parseRepositoryInfoFromURL,
  getPullRequestURLs,
  getGitHubCredentials
};

@@ -148,24 +148,21 @@
 m'%0A%7D);%0A%0A
-function
+const
  getGitH
@@ -174,18 +174,24 @@
 dentials
-()
+ = () =%3E
  %7B%0A  let
@@ -755,26 +755,24 @@
 oken%5D;%0A%7D
+;
 %0A%0A
-function
+const
  authent
@@ -777,18 +777,23 @@
 nticate 
-()
+= () =%3E
  %7B%0A  con
@@ -1070,26 +1070,24 @@
  true;%0A%7D
+;
 %0A%0A
-function
+const
  getRepo
@@ -1095,18 +1095,23 @@
 itories 
-()
+= () =%3E
  %7B%0A  ret
@@ -1219,26 +1219,24 @@
 ct)));%0A%7D
+;
 %0A%0A
-function
+const
  parseRe
@@ -1259,13 +1259,16 @@
 URL 
-(url)
+= url =%3E
  %7B%0A 
@@ -1379,26 +1379,24 @@
  null;%0A%7D
+;
 %0A%0A
-function
+const
  getPull
@@ -1406,16 +1406,18 @@
 uestURLs
+ =
  (pullRe
@@ -1431,16 +1431,19 @@
  branch)
+ =%3E
  %7B%0A  ret
@@ -1525,18 +1525,16 @@
 );%0A%7D
+;
 %0A%0A
-function
+const
  vie
@@ -1547,18 +1547,23 @@
 equests 
-()
+= () =%3E
  %7B%0A  con
@@ -2642,16 +2642,17 @@
 %0A  %7D);%0A%7D
+;
 %0A%0Aexport

Convert functions to ES2015 arrow functions where possible