
import logging

from Qt import QtCore
from sentry_sdk import capture_exception

import auth_session
import utils

from requests.exceptions import RequestException

class AuthUpdater(QtCore.QObject):
    """
    AuthUpdater logs in at startup and re-logs in 24 hours later.
    If authorization failed, then AuthUpdater wants to try again in 30 minutes.
    Doesn't try to log in if username or password is not entered.
    """

    def __init__(self, parent=None):
        super(AuthUpdater, self).__init__(parent)
        self.__auth_to_prodtrack = False
        self.__auth_to_fs_ctrl = False
        self.__auth_to_assetvcs = False
        self.__timer = QtCore.QTimer(self)
        self.__timer.setInterval(30*60*1000) #0.5h
        self.__timer.timeout.connect(self.re_auth)
        self.__currentDateTime = None
        self.log = logging.getLogger("wizart_desktop")


    def have_credentials(self):
        user = utils.get_user()
        if user and utils.get_password(user):
            return True
        else:
            #silently false in case if user never entered credentials
            return False

    def cookies_expired(self, auth_time):
        if auth_time and auth_time.secsTo(self.__currentDateTime) < 24*60*60: #24h
            return False
        return True

    def prodtrack_auth(self):
        result = False
        try:
            result = auth_session.auth_to_prodtrack_and_save()
        except auth_session.WizartDesktopAuthError as e:
            self.log.warning("%s. Check your login and password." % e )
            capture_exception(e)
        except RequestException as e:
            self.log.warning("%s. Connection error." % e )
            capture_exception(e)
        else:
            if result:
                self.__auth_to_prodtrack = self.__currentDateTime

    def fs_ctrl_auth(self):
        result = False
        try:
            result = auth_session.auth_to_fs_ctrl_and_save()
        except auth_session.WizartDesktopAuthError as e:
            self.log.warning("%s. Check your login and password." % e)
            capture_exception(e)
        else:
            if result:
                self.__auth_to_fs_ctrl = self.__currentDateTime

    def assetvcs_auth(self):
        result = False
        try:
            result = auth_session.auth_to_assetvcs_and_save()
        except auth_session.WizartDesktopAuthError as e:
            self.log.warning("%s. Check your login and password." % e)
            capture_exception(e)
        else:
            if result:
                self.__auth_to_assetvcs = self.__currentDateTime

    def auth(self):
        self.__currentDateTime = QtCore.QDateTime.currentDateTime()
        self.prodtrack_auth()
        self.fs_ctrl_auth()
        self.assetvcs_auth()

    def re_auth(self):
        self.log.info('Auto Reauthorize: checking cookies')
        self.__currentDateTime = QtCore.QDateTime.currentDateTime()
        if self.cookies_expired(self.__auth_to_prodtrack):
            self.prodtrack_auth()
        if self.cookies_expired(self.__auth_to_fs_ctrl):
            self.fs_ctrl_auth()
        if self.cookies_expired(self.__auth_to_assetvcs):
            self.assetvcs_auth()

    def run(self):
        if self.have_credentials():
            self.auth()
            self.__timer.start()
        else:
            self.__timer.stop()
