# global import, red is normal don't worry
import network_constants
from env_info import is_running_locally, get_resources_path

import os
import json
import requests

class TokenManager:
    
    _instance = None

    @staticmethod 
    def getInstance():
        ''' Static access method. '''
        if TokenManager._instance == None:
            TokenManager._instance = TokenManager()
        return TokenManager._instance
    
    def __init__(self):
        self._token = None

    def getToken(self) -> str:
        if self._token == None:
            credentials_path = get_resources_path()
            
            print("Looking for credentials at ... "+str(credentials_path))

            with open(f'{credentials_path}/regular_user_credentials.json') as file_handler:
                credentials = json.loads(file_handler.read())
            
            url = f'https://{network_constants.REST_GATEWAY_HOSTNAME}:{network_constants.REST_GATEWAY_REST_PORT}/api/tokens'

            response = requests.post(
                    url,
                    verify = False, 
                    proxies = { "http":None, "https":None },
                    json = credentials
            )

            if response.status_code != 200:
                raise ValueError(f"Server responded with ({response.status_code}): {response.text}")

            data = json.loads(response.text)
            self._token = data["token"]

        return self._token