# global import, red is normal don't worry
import network_constants

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:
            try:
                credentials_path = '../../../modules/security/'
            except KeyError:
                credentials_path = '/srv/articonf/'
            
            print("Looking for credentials at ... "+str(credentials_path))

            with open(f'{credentials_path}regular_user_credentials.json') as file:
                credentials = json.loads(file.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
            )

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

        return self._token