#!/usr/bin/python3
# Copyright (C) 2014 Matěj Cepl
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import configparser
import getpass
import json
import logging
import os
from urllib.request import (HTTPSHandler, build_opener,
                            HTTPPasswordMgrWithDefaultRealm)

from urllib2_prior_auth import HTTPBasicPriorAuthHandler


logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s',
                    level=logging.INFO)

conf_pars = configparser.SafeConfigParser({
    'user': getpass.getuser(),
    'password': None
})
conf_pars.read(os.path.expanduser("~/.githubrc"))
git_user = conf_pars.get('github', 'user')
git_password = conf_pars.get('github', 'password')
if git_password is None:
    raise ValueError('Missing credentials!')

pwd_manager = HTTPPasswordMgrWithDefaultRealm()
pwd_manager.add_password(None, 'https://api.github.com',
                         git_user, git_password)
auth_prior_handler = HTTPBasicPriorAuthHandler(pwd_manager)
verbose_handler = HTTPSHandler(debuglevel=1)

opener = build_opener()
opener.add_handler(verbose_handler)
opener.add_handler(auth_prior_handler)

api_stream = opener.open('https://api.github.com/issues')
iss = json.loads(api_stream.read().decode())

for i in iss:
    print("%s // %s:\n%s\n" % (i['repository']['name'], i['title'], i['url']))
