import os
import http.server
import socketserver
from urllib.parse import urlparse
from urllib.parse import parse_qs

def load_file_content(filename):
    try:
        folder = f"oplaboptionvols"
        #os.makedirs(folder, exist_ok=True)  # Garante que a pasta existe
        file_path = os.path.join(folder, f"{filename}.json") 
        if os.path.exists(file_path):
            print("The file exists.")
            with open(file_path, 'r') as file:
                content = file.read()
                return content
        else:
            print("The file does not exist.")
            return False
    except FileNotFoundError:
        print(f"Arquivo '{file_path}' não encontrado.")
        return False
    #
#


class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # Sending an '200 OK' response
        self.send_response(200)

        # Setting the header
        self.send_header("Content-type", "text/html")

        # Whenever using 'send_header', you also have to call 'end_headers'
        self.end_headers()

        # Process the word 'xxx' if it exists in the path
        parsed_path = urlparse(self.path)
        path_parts = parsed_path.path.split('/')
        if len(path_parts) > 1 and path_parts[1] == 'xxx':
            print(f"Path contains 'xxx': {path_parts}")

        # Extract query param
        name = 'World'
        query_components = parse_qs(urlparse(self.path).query)
        if 'name' in query_components:
            name = query_components["name"][0]
        if 'filename' in query_components:
            # http://34.83.53.117:8000/?filename=PETR4
            filename = query_components["filename"][0]
            
            #file_path = 'path/to/your/file.txt'
            json_response = load_file_content(filename)
            self.send_response(200)
            if json_response:
                json_response = json_response.encode('utf-8')
            else:
                json_response = '{"error": "File not found"}'.encode('utf-8')    
                # Serve JSON when filename is present in the query
                
            #self.send_header("Content-type", "application/json")
            self.send_header("Content-Length", str(len(json_response)))
            self.end_headers()
            
            #json_response = content#'{"a": 1}'
            #self.wfile.write(bytes(json_response, "utf8"))
            self.wfile.write(json_response)
            
            #self.send_header("Content-Length", str(len(json_response)))
            #self.end_headers()
            ##self.wfile.write(bytes('{"error": "File not found"}', "utf8"))
            #self.wfile.write(json_response)
            return
        if 'teste' in query_components:
            filename = query_components["teste"][0]
            # Serve JSON when filename is present in the query
            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            
            json_response = '{"a": 1}'
            self.wfile.write(bytes(json_response, "utf8"))
            
            return

        # Some custom HTML code, possibly generated by another function
        html = f"<html><head></head><body><h1>Hello {name}!</h1></body></html>"

        # Writing the HTML contents with UTF-8
        self.wfile.write(bytes(html, "utf8"))

        return

# Create an object of the above class
handler_object = MyHttpRequestHandler

PORT = 8000
my_server = socketserver.TCPServer(("", PORT), handler_object)

# Star the server
my_server.serve_forever()