from simplewebdev import WebRequestHandler, httpReturn, htmldoc, htmlelement
import platform,socket,re,uuid,json,psutil,logging

def mime_shell(response, mime, status=200):
  return httpReturn(response, [("content-type", mime)], status)

def function(handler: WebRequestHandler):
  return httpReturn(htmldoc(htmlelement("img", src="https://www.liraaa.com/pfp.png")), [("content-type", "text/html")], 200)

def chat(handler: WebRequestHandler):
  response = htmldoc(htmlelement("body", onload="window.scrollTo(0,document.body.scrollHeight);"))
  with open("./chat.txt") as chat:
    for line in chat:
      response += line+"<br>"
  response.background = "#474747"
  return mime_shell(response, "text/html")

def handleChat(post):
  with open("./chat.txt", "a") as chat:
    chat.write("\n"+post)

def chatpost(handler: WebRequestHandler):
  if (post_body := handler.post_data.decode()) == "":
    return mime_shell("this is a post request endpoint not meant for browsing", "text/plain")
  handleChat(post_body)
  return httpReturn("", [], 200)

def getSystemInfo():
  try:
    info={}
    info['platform']=platform.system()
    info['platform-release']=platform.release()
    info['platform-version']=platform.version()
    info['architecture']=platform.machine()
    info['hostname']=socket.gethostname()
    info['ip-address']=socket.gethostbyname(socket.gethostname())
    info['mac-address']=':'.join(re.findall('..', '%012x' % uuid.getnode()))
    info['processor']=platform.processor()
    info['ram']=str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB"
    info["ram used"]=str(psutil.virtual_memory().percent)
    info["cpu usage (%)"]=str(psutil.cpu_percent())
    return json.dumps(info)
  except Exception as e:
    logging.exception(e)
  
def jsontohtml(jsondata: str):
  jsondata = json.loads(jsondata)
  main = htmldoc()
  for element in jsondata:
    newelement = htmlelement(element.tag, **element["attrs"])
    for child in element["children"]:
      jsontohtml(child)
    

def SysInfo(handler: WebRequestHandler):
  if "raw" in handler.query_data:
    return httpReturn(getSystemInfo(), [("content-type", "application/json")], 200)
  return httpReturn(getSystemInfo(), [("content-type", "text/html")], 200)

paths = {
  "test": function,
  "chat": chat,
  "chatpost": chatpost,
  "info": SysInfo,
  # "simplewebdev.py": lambda handler: mime_shell('{"msg": "youve now bee hacked"}', "application/json")
}

disallow = [
#   "main.py",
#   "assets/test_file.txt",
#   "simplewebdev.py",
#   "responses.py",
#   "datatypes.py",
#   "server.py",
#   "assets"
]
