#!/usr/bin/env python3

from i3dstatus.block import Block

import time
import requests
import atexit
from requests.exceptions import ConnectionError
import os
import asyncio

block = Block(os.path.basename(__file__))

# display aggregate info on your users github repos

block_name = 'github-repos'
format_str = '<span color="yellow">★</span>%stars <small>?</small>%issues'
users = ['altdesktop']
interval = 600


async def show_block(stars, issues, watchers):
    context = {
        'users': ', '.join(users),
        'stars': str(stars),
        'issues': str(issues),
        'watchers': str(watchers),
    }

    await block.show(format_str, context=context, markup='pango')


async def get_repo_stats():
    stars = 0
    issues = 0
    watchers = 0

    try:
        for user in users:
            page = 1
            while True:
                url = 'https://api.github.com/users/%s/repos' % user
                repos = requests.get(url, params={'page': page}).json()
                page += 1

                if not repos:
                    break

                for r in repos:
                    stars += r['stargazers_count']
                    issues += r['open_issues_count']
                    watchers += r['watchers_count']

        await show_block(stars, issues, watchers)
    except ConnectionError:
        # oops couldn't connect
        pass


async def main():
    global block_name, format_str, users, interval

    await block.connect()

    if 'users' in block.config:
        users = block.config['users']

    if 'format' in block.config:
        format_str = block.config['format']

    if 'interval' in block.config:
        interval = block.config['interval']

    while True:
        await get_repo_stats()
        await asyncio.sleep(300)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
