# -*- coding: utf-8 -*-
#
from xbmcutils import logger, config
from trakt import Trakt, ClientError, ServerError

class traktAPI(object):
    __apikey = "d4161a7a106424551add171e5470112e4afdaf2438e6ef2fe0548edc75924868"
    __token = ""
    __username = ""
    __password = ""
    __enabled = False

    def __init__(self):
        logger.debug("Initializing.")
        self.__enabled = config.get_setting('trakt_enabled') == "true"

        if self.__enabled:
            # Get user login data
            self.__username = config.get_setting('username')
            self.__password = config.get_setting('password')

            # Configure
            Trakt.configuration.defaults.client(
                id=self.__apikey
            )

            if not self.__token:
                self.getToken()

    def getToken(self):
        # Attempt authentication (retrieve new token)
        if self.__username and self.__password:
            with Trakt.configuration.http(retry=True):
                try:
                    auth = Trakt['auth'].login(self.__username, self.__password)
                    if auth:
                        self.__token = auth
                    else:
                        logger.debug("Authentication Failure")
                except Exception as ex:
                    logger.fatal(ex.message)

    def getShowsWatched(self, shows):
        if self.__enabled:
            if not self.__token:
                self.getToken()

            if self.__token:
                with Trakt.configuration.auth(self.__username, self.__token):
                    with Trakt.configuration.http(retry=True, timeout=90):
                        Trakt['sync/watched'].shows(shows, exceptions=True)
                return shows
        return shows
