from html import escape
from urllib.parse import parse_qs
import sys
import importlib

sys.path.append("/opt")
sys.path.append("/home/sparky2021/workspace_pseminar")

from snackxpress.python import util

def application (environ, start_response):

    # Returns a dictionary in which the values are lists
    d = parse_qs(environ['QUERY_STRING'])
    par = {}
    for key in d.keys():
        par[key] = d[key][0]


    if "DEBUG_REQUEST" in par:
    #if True:
        outstr = "Request-Parameter:\n\n"
        for key in environ.keys():
            outstr += f"{key}: {repr(environ[key])}\n"
        
        outstr +="\nParameter:\n\n"
        
        for key in par.keys():
            outstr += f"{key}: {par[key]}\n"
            
        outstr += "PATH: "+ str(sys.path)
        
        # prepare output
        status = '200 OK'
        response_headers = [
            ('Content-Type', 'text/plain'),
            ('Content-Length', str(len(outstr)))
        ]
    
        start_response(status, response_headers)
        return [outstr.encode("utf-8")]

    mod_str = environ["PATH_INFO"]
    if mod_str == "/" or mod_str == "":
        mod_str = "/index"
    mod_path = "snackxpress"+mod_str.replace("/", ".")
    
    try:
        util.schreibe_log(f"mod_path: {mod_path}")
        mod = importlib.import_module(mod_path)
        
        html = mod.index(environ, par)
    
    except Exception as e:
        
        util.schreibe_log("Exception: "+str(e))
        html = """
<html>
<body>
<h1>Fehler</h1>
<p>Informieren Sie den Systembetreuer (mwd)</p>
</body>
</html>
"""

    status = '200 OK'

    # Now content type is text/html
    response_headers = [
        ('Content-Type', 'text/html'),
        ('Content-Length', str(len(html)))
    ]

    start_response(status, response_headers)
    return [html.encode("utf-8")]
        
