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

__all__ = ['AUTH_PATH', 'Auth', 'auth', 'path', 'login', 'logout', 'signup']

# Cell
import base64
import os
import getpass
import requests

# Cell
from .conf import CLI_ENDPOINT, API_ENDPOINT, TIGHTAI_LOCAL_DIRECTORY, TIGHTAI_LOCAL_CREDENTIALS
from .handlers import credentials

AUTH_PATH = TIGHTAI_LOCAL_CREDENTIALS

# Cell
class Auth:
    def username_input(self, label='Username / Email'):
        username = input("{label}: ".format(label=label))
        if username == None or username == "":
            print("Username is required. \n")
            return self.username_input()
        return username

    def email_input(self):
        email = input("Email: ")
        if email == None or email == "":
            print("Email is required. \n")
            return self.email_input()
        return email

    def password_input(self, label='Password (typing hidden on purpose)'):
        pw = getpass.getpass("{label}: ".format(label=label))
        if pw == None or pw == "":
            print("Password is required. \n")
            return self.password_input()
        return pw

    def login(self, username=None, password=None):
        if username is None:
            username = self.username_input()
        if password is None:
            password = self.password_input()
        TIGHTAI_LOCAL_DIRECTORY.mkdir(parents=True, exist_ok=True)
        data = {"username": username, "password": password}
        cli_login = f"{CLI_ENDPOINT}/login/"
        r = requests.post(cli_login, data=data)
        if r.status_code in range(200, 299):
            response_data = r.json()
            user = response_data.get("user")
            token = response_data.get("token")
            if user is not None:
                username = user.get('username')
            credentials.to_environ(username=username, token=token)
            credentials.to_file(username=username, token=token)
            print("You are now logged in")
            #return True
        else:
            try:
                response = r.json()
            except:
                return "There was an error in your request."
            if "non_field_errors" in response:
                errors = response['non_field_errors']
                for e in errors:
                    print(e)
                #return None
        #return True

    def logout(self):
        return credentials.remove()

    def signup(self):
        username                 = self.username_input(label='Username')
        email                    = self.email_input()
        password                 = self.password_input(label='Password')
        confirm_password         = self.password_input(label='Confirm Password')
        if confirm_password != password:
            print("Passwords do not match. Please try again.")
            password                 = self.password_input(label='Password')
            confirm_password         = self.password_input(label='Confirm Password')
        data = {"username": username, "email": email, "password": password, "password2": confirm_password}
        cli_login = "{base_endpoint}/register/".format(base_endpoint=CLI_ENDPOINT)
        r = requests.post(cli_login, data=data)
        if r.status_code in range(200, 299):
            response_data = r.json()
            print("You are now registered. \nPlease confirm your email. \nWe wil send you a confirmation from `hi@tight.ai` shortly.\nThank you.")
            user = response_data.get("user")
            token = response_data.get("token")
            if user is not None:
                username = user.get('username')
            credentials.to_environ(username=username, token=token)
            credentials.to_file(username=username, token=token)
            #return True
        else:
            try:
                response = r.json()
            except:
                return "There was an error in your request."
            if "non_field_errors" in response:
                errors = response['non_field_errors']
                for e in errors:
                    print(e)
                #return None
        #return True


auth      = Auth()
path      = AUTH_PATH
login     = auth.login
logout    = auth.logout
signup    = auth.signup
