import urllib2

from application.model import ApplierSubTypes
from application.model.configuration import Configurations


class LoyaltyAvailableInteractor(object):
    def __init__(self, configs):
        # type: (Configurations) -> None

        self.is_loyalty_enabled = configs.is_loyalty_enabled
        self.url_to_test = configs.credentials[ApplierSubTypes.LOYALTY].base_url
        self.logger = configs.logger

    def is_loyalty_available(
        self,       # type: LoyaltyAvailableInteractor
    ):
        # type: () -> bool

        if not self.is_loyalty_enabled:
            return False

        return self._test_loyalty_connection()

    def _test_loyalty_connection(
        self,       # type: LoyaltyAvailableInteractor
    ):
        # type: () -> bool

        try:
            self.logger.debug('Url to test: "{}"'.format(self.url_to_test))
            urllib2.urlopen(self.url_to_test, timeout=10)
            self.logger.debug('Test OK')
            return True
        except urllib2.HTTPError:
            self.logger.debug('Test OK')
            return True
        except urllib2.URLError as e:
            self.logger.debug('Could not connect to the provided URL', exc_info=e)
            return False
        except ValueError as e:
            self.logger.debug('DNS Server is unreachable', exc_info=e)
