# BrainGenix-NES
# AGPLv3

import requests

class RequestHandler:

    def __init__(self, _URIBase:str, _Token:str):
        self.URIBase = _URIBase
        self.Token = _Token

        # Check that API is up
        try:
            Response = requests.get(f"{self.URIBase}/Hello")
        except:
            raise ConnectionError("Unable To Connect To API Endpoint")
        

    
    # Make Query
    def MakeQuery(self, _URIStub:str):
        
        # Exception Handling For Network Errors
        Response = None
        for RetryCount in range(5):
            try:
                Response = requests.get(f"{self.URIBase}{_URIStub}")
                break
            except requests.exceptions.ChunkedEncodingError as E:
                if (RetryCount == 4):
                    raise ConnectionError("Error Communicating With API, An IncompleteRead Has Occured!")
                else:
                    print("\n---------------")
                    print(f"Warning, Attempt {RetryCount} Has Failed, Retrying Query {self.URIBase}{_URIStub}")
                    print(f"Python Reports Error: {E}")
                    print("---------------\n")

        # Parse the Response, Return It
        ResponseJSON = Response.json()
        if (ResponseJSON["StatusCode"] != 0):
            raise ConnectionError(f"Error During API Call To '{self.URIBase}{_URIStub}', API Returned Status Code '{ResponseJSON['StatusCode']}'")
            return None
        return ResponseJSON


    def MakeAuthenticatedQuery(self, _URIStub:str):
        URIStub = f"{_URIStub}&AuthKey={self.Token}"
        return self.MakeQuery(URIStub)