import socket

addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen()

lcd1.clear()
lcd1.print('LCData')
lcd1.set_cursor_pos(2,1)
lcd1.print(f'http://{addr[0]}:{addr[1]}')

PATHS = {
	'/': {

	}
}

def url_decode(url_encoded_str):
	data = bytearray()
	i = 0
	l = len(url_encoded_str)
	while i < l:
		if url_encoded_str[i] != '%':
			# Handle spaces encoded as '+' in query strings
			if url_encoded_str[i] == '+':
				data.append(ord(' '))
			else:
				data.append(ord(url_encoded_str[i]))
			i += 1
		else:
			# Decode the percent-encoded character (e.g., '%20')
			try:
				hex_code = url_encoded_str[i+1:i+3]
				char_code = int(hex_code, 16)
				data.append(char_code)
				i += 3
			except (ValueError, IndexError):
				# In case of invalid encoding, retain the '%' and move on
				data.append(ord('%'))
				i += 1
	return data.decode('utf-8')

def main():
	try:
		while True:
			try:
				conn, addr = s.accept()
				print(f'Accepted connection: {addr}')
				request = conn.recv(1024)
				request = request.decode('UTF-8')
				request = request.split('\r')[0] # Don't care about headers
				print(request)

				#PARSEREQUEST
				try:
					method, path, http_ver = request.split() # Seperate request
				except ValueError:pass
				print(f'{http_ver=} | {path=} | {method=}')
				if not '?' in path:
					path += '?'
				path, paramstr = path.split('?') # Seperate parameters from path
				paramstrs = paramstr.split('&') # Seperate parameters
				params = {} # We'll put them in a dict for ease
				for param in paramstrs:
					split = param.split('=')
					if len(split) == 2:
						params[split[0]] = url_decode(split[1])
				print(f'{params=}')

				#GENERATERESPONSE
				if path == '/': # Root
					headers = 'HTTP/1.1 200 OK\r\nContent-type: text/plain\r\n\r\n'
					body = '''
LCD Print
/clear - Clear screen.
/print?text={str} - Print text.
/set_cursor_pos?line={int}&col={int} - Set the cursor position.
\r\n\r\n
'''
				elif path == '/clear': # Clear screen
					lcd1.clear()
					headers = 'HTTP/1.1 201 Created\r\nContent-type: text/plain\r\n\r\n'
					body = 'Done\r\n\r\n'
				elif path == '/print': # Print text
					lcd1.print(params['text'])
					headers = 'HTTP/1.1 201 Created\r\nContent-type: text/plain\r\n\r\n'
					body = 'Done\r\n\r\n'
				elif path == '/set_cursor_pos':
					lcd1.set_cursor_pos(int(params['line']),int(params['col']))
					headers = 'HTTP/1.1 201 Created\r\nContent-type: text/plain\r\n\r\n'
					body = 'Done\r\n\r\n'
				elif path == '/display':
					lcd1.display(int(params['visible']),int(params['cursor']),int(params['cursor_blink']))
					headers = 'HTTP/1.1 201 Created\r\nContent-type: text/plain\r\n\r\n'
					body = 'Done\r\n\r\n'
					
				else: # Anything else
					headers = 'HTTP/1.1 404 Not Found\r\nContent-type: text/plain\r\n\r\n'
					body = 'Not Found\r\n\r\n'
				conn.send(headers)
				conn.send(body)
				conn.close()
			except OSError:
				pass
	except KeyboardInterrupt:pass
	
if __name__ == '__main__':
	main()
