#!/usr/bin/python3

import cgi, cgitb
cgitb.enable()

import sys, os
import importlib
import traceback

d = cgi.FieldStorage()
par = {}
for key in d.keys():
    par[key] = d[key].value

req = {}

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

from snackxpress.python import util
from snackxpress.python.redirect_exception import RedirectException

if "DEBUG_REQUEST" in par:
#if True:
    outstr = "Request-Parameter:\n\n"
    
    for key in par.keys():
        outstr += f"{key}: {par[key]}\n"
        
    outstr += "PATH: "+ str(sys.path)
    
    # prepare output
    print("Content-Type: text/plain;charset=utf-8")
    print()    
    print(outstr)
    exit()

if "DEBUGGER" in par:
#if True:
    sys.path.append("/home/sparky2021/.eclipse/org.eclipse.platform_4.18.0_1473617060_linux_gtk_x86_64/plugins/org.python.pydev.core_8.3.0.202104101217/pysrc/")
    import pydevd
    pydevd.settrace()

mod_str = os.environ["REDIRECT_URL"]
if redirect_url == "/snackxpress/info.py":
    cgi.test()
mod_path = mod_str[1:].replace(".py","").replace("/", ".")

try:
    util.schreibe_log(f"mod_path: {mod_path}")
    mod = importlib.import_module(mod_path)
    
    html = mod.index(req, par)

except RedirectException as e:
    print("Status: 303 see other")
    print(f"Location: {e}")
    print("Connection: close")
    print()
    exit    

except Exception as e:
    trace = traceback.format_exc(limit=None, chain=True)
    util.schreibe_log("Exception: "+str(e))
    util.schreibe_log(trace)
    html = """
<html>
<body>
<h1>Fehler</h1>
<p>Informieren Sie den Systembetreuer (mwd)</p>
</body>
</html>
"""


print("Content-Type: text/html;charset=utf-8")
print()    
print(html)
