import os
import requests
from requests.exceptions import ConnectionError


class Authentication:

    def __init__(self):
        self.config_file = os.path.expanduser('~/.ares_l.txt')
        self.api = "https://backend-ares-production.up.railway.app/api/check-license/"
        self.message  = "processing"

    def check_auth(self) -> bool:
        if os.path.exists(self.config_file):
            return True
        else:
            return False
    
    def progress_message(self) -> str:
        return self.message
    
    def __save_license_key(self, license_key) -> None:
        with open(self.config_file, 'w') as f:
            f.write(license_key)

    def __load_config_file(self) -> None:
        already_logged_in = self.check_auth()

        if already_logged_in:
            with open(self.config_file, "r") as conf_file:
                self.message = "found"
                return conf_file.read().strip()
        else:
            self.message = "notfound"
            LICENSE_KEY = input("Enter you license key:__ ")
            return LICENSE_KEY
        
    def validate_license_key(self) -> bool:
        try:
            key = self.__load_config_file()
            response = requests.post(self.api, json={"token": f"{key}"})
            if response.status_code == 200:
                self.__save_license_key(key)
                return True
            else:
                return False
        except ConnectionError:
            self.message = "connection"
            print("Cannot complete your request check you connection")