#! /usr/bin/env python3

import argparse
import json
import time

from perceval.backends.core.github import GitHub

token = [""]

# Parse command line arguments
parser = argparse.ArgumentParser(
    description = "Simple parser for GitHub issues and pull requests"
    )
# parser.add_argument("-t", "--token",
#                     '--nargs', nargs='+',
#                     help = "GitHub token")
parser.add_argument("-r", "--repo",
                    help = "GitHub repository, as 'owner/repo'")
args = parser.parse_args()

# Owner and repository names
(owner, repo) = args.repo.split('/')

# create a Git object, pointing to repo_url, using repo_dir for cloning
repo = GitHub(owner=owner, repository=repo, api_token=token)

# fetch all issues/pull requests as an iterator, and iterate it printing
# their number, and whether they are issues or pull requests

try:
    timeinfo = time.gmtime()
    timevalue = "{:04d}{:02d}{:02d}".format(timeinfo.tm_year, timeinfo.tm_mon, timeinfo.tm_mday)
    with open(args.repo.replace("/", "_") + "-" + timevalue + "-issues.json", 'a') as ioutput:
        with open(args.repo.replace("/", "_") + "-" + timevalue + "-pulls.json", 'a') as poutput:
            for item in repo.fetch():
                if 'pull_request' in item['data']:
                    kind = 'Pull request'
                    json.dump(item['data'], poutput, indent=4)
                else:
                    kind = 'Issue'
                    json.dump(item['data'], ioutput, indent=4)


# should anything go wrong, log it in an error file
except Exception as Argument:
    timevalue = "{:04d}{:02d}{:02d}".format(timeinfo.tm_year, timeinfo.tm_mon, timeinfo.tm_mday)
    with open(args.repo.replace("/", "_") + "-" + timevalue + ".errors.txt", 'a') as errorsOutput:
        errorsOutput.write(str(Argument))

