import requests, json, subprocess, re, os
from pathlib import Path
from datatypes import htmlelement, htmldoc, headers, httpReturn
from urllib.parse import unquote

def error(handler, code: int, message: str = ""):
  match code:
    case 403:
      return httpReturn(f"you are not authorized to access the file at /{handler.url.path.removesuffix("/").removeprefix("/")}<br><br>"+message, [("Content-Type", "text/html")], 403)
    case 404:
      return httpReturn("404 not found<br><br>"+message, [("Content-Type", "text/html")], 404)
    case _:
      return httpReturn(f"error {code}<br><br>"+message, [("Content-Type", "text/html")], code)
    
def lsdir(handler, root: str, unauthorized: list = []):
  file: str = root+unquote(handler.url.path.removesuffix("/").removeprefix("/"))
  dir = os.listdir(file)
  unauthorized = unauthorized.copy()
  for each in range(len(unauthorized)):
    unauthorized[each] = root+unauthorized[each]
  topop = []
  for files in range(len(dir)):
    if (file+"/"+dir[files]).replace("//", "/") in unauthorized:
      topop.append(files)
  for files in sorted(topop, reverse=True):
    dir.pop(files)
  response = htmldoc()
  thing = handler.url.path.removesuffix("/").removeprefix("/").split("/")
  thing.pop()
  var = "/"
  for yah in thing:
    var+=yah+"/"
  response += htmlelement("div").contain(". . /").link(var)
  for files in dir:
    response += htmlelement("div").contain(files).link(f"{"/"+unquote(handler.url.path.removesuffix("/").removeprefix("/")) if unquote(handler.url.path.removesuffix("/").removeprefix("/")) != "" else ""}/{files}")
  return httpReturn(response, [("content-type", "text/html")], 200)
  
def giveheadersback(handler):
  response = ""
  for header in handler.headers.items():
    response += header[0]+", "+header[1]+"<br>"
  return httpReturn(response, [("Content-Type", "text/html")], 200)

def get_file(handler, root: str):
  file: str = unquote(handler.url.path.removesuffix("/").removeprefix("/")) # if handler.url.path.removesuffix("/").removeprefix("/") not in exceptions else exceptions[handler.url.path.removesuffix("/").removeprefix("/")]
  match file.split(".")[len(file.split("."))-1]:
    case "css":
      file_mime = "text/css"
    case "js":
      file_mime = "text/javascript"
    case "py":
      file_mime = "text/plain"
    case "txt":
      file_mime = "text/plain"
    case _:
      file_mime = subprocess.getoutput('file -bi "'+root+file+'"').split(";")[0]
  file_contents = Path(root+file).read_bytes()
  return httpReturn(file_contents, [("Content-Type", file_mime)], 200)

def get_file_direct(file):
  file_mime = subprocess.getoutput(f'file -bi {file}').split(";")[0]  
  file_contents = Path(file).read_bytes()
  return httpReturn(file_contents, [("Content-Type", file_mime)], 200)

paths = {
  "headers": giveheadersback,
}