main = """
import socket
import sys
import cache.handle as handle
from threading import Thread

#initiate socket
sock = socket.socket()
sock.bind(('127.0.0.1', 8000))
print(f'server hosted at {sock.getsockname()}')
print('initiating framework')
sock.listen(10)

THREADS = []
CONNS = []

#listen for connections
while True:
    try:
        conn, addr = sock.accept()

        CONNS.append(conn)
        t = Thread(target=handle.Handler, args=[conn,])
        t.setDaemon(True)
        THREADS.append(t)
        t.start()
    except KeyboardInterrupt:
        print('shutting down server')
        sock.close()
        sys.exit()"""

handle = """
import sys
from urls import *
import cache.exceptionHandling as eH

'''
This is the request handling file, all the requests go through here and get resolved,
do not edit this file unless you know what you are doing!!!
'''



class Handler:
    def __init__(self, conn):
        self.conn = conn
        self.data = {}
        self.startrecv()
        self.resolvePath()

    def startrecv(self):

        msg = self.conn.recv(1024*100).decode()

        self.readmsg(msg)

    def readmsg(self, request):
        body = None
        try:
            header, body = request.split('\\r\\n\\r\\n')
        except Exception:
            # header = request
            print(request.split('\\r\\n\\r\\n'))
            sys.exit()


        lines = header.split('\\r\\n')
        l1 = lines[0]
        try:
            self.data['method'], path, version = l1.split(' ')
        except Exception as e:
            print(str(e))
            sys.exit()
        print(self.data['method'], path, version)


        # get GET data
        self.PATH = path
        try:
            self.PATH, GET_DATA = path.split('?')
            DATA = GET_DATA.split(';')
            varis = []
            dats = []
            for data in DATA:
                var, dat = data.split('=')
                varis.append(var)
                dats.append(dat)
            GET_DATA = {v:d for v,d in zip(varis, dats)}
            self.GET = GET_DATA
            print(GET_DATA)
        except Exception:
            pass

        # get POST data
        if body is not None:

            POST_DATA = body.split('&')
            vars = []
            datas = []

            try:
                for data in POST_DATA:
                    var, dat = data.split('=')
                    vars.append(var)
                    datas.append(dat)
                self.POST = {v:d for v,d in zip(vars, datas)}

            except Exception:
                pass

    def resolvePath(self):

        try:
            if self.PATH[:8] == '/static/':
                self.conn.send(static_handler(self.PATH))
                self.conn.close()


            for path in URL_PATTERNS.keys():
                if self.PATH == path:

                    self.conn.send(URL_PATTERNS[path].__call__(self))
                    self.conn.close()

            self.conn.send(eH.Error.R404)

        # except Exception as e:
        #     print(str(e))
        #     self.conn.send(eH.Error.R500)
        #     self.conn.close()

        finally:
            print('handle success')
            sys.exit()
"""
httpResponses = """
import os
from jinja2 import Template


class HTTPResponse:
    R200 = b"HTTP/1.1 200 OK\\r\\nServer: My server\\r\\nContent-Type: text/html\\r\\nConnection: Closed\\r\\n\\r\\n"
    R404 = b"HTTP/1.1 404 Not Found\\r\\nServer: My server\\r\\nContent-Type: text/html\\r\\nConnection: Closed\\r\\n\\r\\n"
    R500 = b'HTTP/1.1 500 Internal Server Error\\r\\n\\r\\n'
    RET = ''

    def __init__(self, doc=None, content=None, code=200):
        if type(content) == str:
            content = content.encode()
        if content is None:
            try:
                content = open(doc).read().encode('utf-8')
            except Exception:
                content = b''
        if code == 200:
            self.RET = self.R200+content
        if code == 404:
            self.RET = self.R404+content
        if code == 500:
            self.RET = self.R500+content





class Render:
    def __init__(self, doc: str, content=None):
        if content is not None:
            doc = Template(open(doc).read())
            self.RET = doc.render(content)
        else:
            self.RET = open(doc).read()

        self.RET = HTTPResponse(content=self.RET).RET

"""

exception = """
class Error:
    R404 = b"HTTP/1.1 404 Not Found\\r\\nServer: My server\\r\\nContent-Type: text/html\\r\\nConnection: Closed\\r\\n\\r\\n<h1 style='text-align: center;'>404 not found</h1>"
    R500 = b"HTTP/1.1 500 Internal Server Error\\r\\n\\r\\n<h1 style='text-align: center;'>500 Internal Server Error</h1>"
"""

urls = """from cache.httpResponses import *
import os
import cache.exceptionHandling as eH
import sqlite3


def static_handler(path):
    path = f'.{path}'
    header = 'HTTP/1.0 200 OK\\r\\nContent-Type: image/png\\r\\nContent-Length: {}\\r\\n\\r\\n'.format(os.path.getsize(path))
    try:
        file = open(path, 'rb')
        header = header.encode()
        cxt = file.read()

        return header+cxt
    except OSError:
        return eH.Error.R404

def index(request):
	return HTTPResponse(content='<center>Framy setup successful</center>').RET

URL_PATTERNS = {

    '/': index,
}
"""