import os
import logging


class ServiceToken(object):
    LOGGER = logging.getLogger(__name__)

    def __init__(self, service_name, token=None):
        self.service_name = service_name
        self.token = token

    def get_token_from_env(self):
        possible_env_vars = [
            'OAUTH_{}'.format(self.service_name.upper()),
            '{}_OAUTH'.format(self.service_name.upper()),
            '{}_TOKEN'.format(self.service_name.upper()),
            '{}_OAUTH_TOKEN'.format(self.service_name.upper())
        ]

        for env_var in possible_env_vars:
            if env_var in os.environ:
                self.token = os.environ[env_var]
                return self.token

    def get_token_from_homedir(self, homedir_path=None):
        try:
            if homedir_path is None:
                homedir_path = os.environ['HOME']
            token_path = '{}/.{}/token'.format(homedir_path, self.service_name)
            # Check token file permissions
            if os.access(token_path, os.R_OK):
                with open(token_path, 'r') as token_file:
                    self.token = token_file.read().strip()
                    return self.token
        except Exception as e:
            self.LOGGER.warn("Can't get token from home directory, %s", e)

    def get_token(self):
        if self.token is not None:
            return self.token
        if self.get_token_from_env() is not None:
            return self.token
        if self.get_token_from_homedir() is not None:
            return self.token


class ServiceTokenStore(object):
    tokens = {}
    clients = {}

    @classmethod
    def get_token(cls, service):
        service = service.lower()
        if cls.tokens.get(service, None) is None:
            token = ServiceToken(service).get_token()
            if token:
                cls.tokens[service] = token
            else:
                raise RuntimeError('Can\'t obtain {} token'.format(service))
        return cls.tokens[service]


if __name__ == '__main__':
    pass
