# AUTOGENERATED! DO NOT EDIT! File to edit: 10_handlers.ipynb (unless otherwise specified).

__all__ = ['CredentialHandler', 'credentials']

# Cell
import base64
import os
from .conf import USER_HOME, TIGHTAI_LOCAL_DIRECTORY, TIGHTAI_LOCAL_CREDENTIALS


class CredentialHandler:
    def to_environ(self, username=None, token=None):
        if username is None or token is None:
            raise Exception("Username and Token are required.")
        os.environ['TIGHTAI_USER'] = username
        os.environ['TIGHTAI_TOKEN'] = token
        return

    def get_username(self):
        username, _        = self.from_file()
        return username

    def get_encoded_token(self):
        username, token        = self.from_file()
        username_token         = "{username}:{token}".format(username=username, token=token)
        encoded                = base64.b64encode(username_token.encode())
        return encoded.decode()


    def from_file(self):
        if not TIGHTAI_LOCAL_CREDENTIALS.exists():
            msg = "Tight.ai credentials not found.\n\nSign up:\nhttps://tight.ai/signup.\n\nLogin:\n$ python -c \"from tightai.auth import login; login();\"\nor\n$ tight login\n"
            print(msg)
            raise Exception(msg)
        with open(TIGHTAI_LOCAL_CREDENTIALS) as inf:
            username = None
            token = None
            for line in inf:
                line = line.split('=')
                line[0] = line[0].strip()
                if line[0] == 'TIGHTAI_USER':
                    username = line[1].strip().replace("'", "").replace('"', '')
                elif line[0] == 'TIGHTAI_TOKEN':
                    token = line[1].strip().replace("'", "").replace('"', '')
            self.to_environ(username=username, token=token)
            return username, token
        return

    def remove(self):
        if TIGHTAI_LOCAL_CREDENTIALS.exists():
            TIGHTAI_LOCAL_CREDENTIALS.unlink()
            print("Successfully logged out.")
            return
        print("Not logged in. Do you need to run tightai.login()?")
        return

    def to_file(self, username=None, token=None):
        if username is None or token is None:
            raise Exception("Username and Token are required.")
        if TIGHTAI_LOCAL_CREDENTIALS.exists():
            TIGHTAI_LOCAL_CREDENTIALS.parent.mkdir(parents=True, exist_ok=True)
        with open(TIGHTAI_LOCAL_CREDENTIALS, 'w') as cred_txt:
            docstring = f"[apikey]\nTIGHTAI_USER='{username}'\nTIGHTAI_TOKEN='{token}'"
            cred_txt.writelines(docstring)
            return True
        return None


credentials = CredentialHandler()