#!/usr/bin/env python
import fire
import requests
import json
import os

GITHUB_ACCESS_TOKEN = os.environ.get("GITHUB_ACCESS_TOKEN", None)

class Gittersect(object):
    '''A commandline utility comparing followers between two users and returning the intersection between them'''

    def single_user(self, name):
        headers = None
        if GITHUB_ACCESS_TOKEN:
            headers = {'Authorization': 'token ' + GITHUB_ACCESS_TOKEN}
        session = requests.Session()
        
        url = ''.join(['https://api.github.com/users/', name, '/followers'])
        response = json.loads(session.get(url, headers=headers).text)
        
        if 'message' in response:
            return response
        
        return self.extract_login(response)

    def extract_login(self, followers):
        followers_login = [] 
        for follower in followers:
            followers_login.append(follower.get('login'))
        return followers_login

    def compare_users(self, user1, user2):
        user1_followers = self.single_user(user1)
        user2_followers = self.single_user(user2)

        if 'message' in user1_followers:
            return 'Error on ' + user1 + ' ' + user1_followers.get('message')

        if 'message' in user1_followers:
            return 'Error on ' + user2 + ' ' + user2_followers.get('message')

        intersecting_followers = set(user1_followers).intersection(user2_followers) 

        if len(intersecting_followers) == 0:
            return 'No matches found!'
        return intersecting_followers

def main():
    gittersect = Gittersect()
    fire.Fire(gittersect.compare_users)

if __name__ == '__main__':
    main()
