#!/usr/bin/env python

import os
import sys

if (len(sys.argv) < 2):
    print("Usage: " + sys.argv[0] + " github-user [github-project]")
    exit(1)

try:
   import requests
except ImportError:
    print("Error: requests is not installed")
    print("Installing Requests is simple with pip:\n  pip install requests")
    print("More info: http://docs.python-requests.org/en/latest/")
    exit(1)


def dict_to_object(d):
    if '__class__' in d:
        class_name = d.pop('__class__')
        module_name = d.pop('__module__')
        module = __import__(module_name)
        class_ = getattr(module, class_name)
        args = dict((key.encode('ascii'), value) for key, value in d.items())
        inst = class_(**args)
    else:
        inst = d
    return inst


repos = []
headers = {}

if "GITHUB_TOKEN" in os.environ:
    headers["Authorization"] = "token %s" % os.environ["GITHUB_TOKEN"]

if len(sys.argv) == 3:
    d = {
        'full_name': sys.argv[1] + "/" + sys.argv[2],
        'name': sys.argv[2],
    }
    repos.append(d)
else:
    r = requests.get('https://api.github.com/users/' + sys.argv[1] + '/repos', headers=headers)
    myobj = r.json()

    for rep in myobj:
        d = {
            'full_name': str(rep['full_name']),
            'name':      str(rep['name']),
        }
        repos.insert(0, d)


for repo in repos:
    full_name = repo['full_name']
    name = repo['name']
    name_col = '%-10s' % name if len(repos) > 1 else ''

    total_count = 0
    try:
        r = requests.get('https://api.github.com/repos/' + full_name + '/releases', headers=headers)
        myobj = r.json()

        for p in myobj:
            if "assets" in p:
                for asset in p['assets']:
                    total_count += asset['download_count']
                    date = asset['updated_at'].split('T')[0]
                    print('%d\t%s %s\t%s'%(
                        asset['download_count'],
                        name_col,
                        date,
                        asset['name'],
                    ))
            else:
                print("No data")
    except:
        pass
    print('%d\t%s Total Downloads' % (total_count, name_col))

