import json
import time
from bento import config
from urllib import request, error

MODE_API = 'API'
MODE_TMI = 'TMI'

class API(object):

    def __init__(self):
        self.channel_name = config.app['channel'][1:]
        self.cache = {'followers': [], 'viewers': [], 'stream': False}
        self.last_viewer_update = time.time()


    def get_viewers(self):
        if time.time() - self.last_viewer_update < 300 and len(self.cache['viewers']):
            return self.cache['viewers']
        
        data = self._call('/group/user/{}/chatters', (self.channel_name,), mode=MODE_TMI)

        if data:
            self.cache['viewers'] = data
            self.last_viewer_update = time.time()

        return data


    def get_stream(self):
        if self.cache['stream']:
            return self.cache['stream']['stream']

        stream = self._call('/streams/{}', (self.channel_name,))

        if stream['stream']:
            self.cache['stream'] = stream['stream']

        return self.cache['stream']


    def is_follower(self, username):
        if username.lower() in self.cache['followers']:
            return True

        if self._call('/users/{}/follows/channels/{}', (username, self.channel_name)):
            self.cache['followers'].append(username)
            return True

        return False


    def in_viewer_list(self, username):
        viewers = self.get_viewers()
        if not viewers:
            return False

        viewers = [user for values in viewers['chatters'].values() for user in values]

        return username.lower() in viewers


    def _call(self, url, data, mode=MODE_API):
        uri = ''

        if mode == MODE_API:
            uri = 'https://api.twitch.tv/kraken'
        elif mode == MODE_TMI:
            uri = 'https://tmi.twitch.tv'

        try:
            req = request.Request(uri + url.format(*data))
            req.add_header('Accept', 'application/vnd.twitchtv.v3+json')
            req.add_header('Client-ID', '9b0hpskgt0i87pxokh835diom2bir47')
            data = json.loads(request.urlopen(req).read().decode('utf-8'))
            
            return data
        except Exception as e:
            # print("Twitch API returned an error: {}".format(e))
            return False