import tkinter as tk
from tkinter import ttk
import socket
import ssl
#import time
#import threading

class Protocols:
	p={
	"gemini":{"port":1965,"TLS":True},
	"https":{"port":443,"TLS":True}
	}
	def Get(host: str, user=None, port=None, path=None, q=None, frag=None):
		pass
	def CreateTLS(host: str, port: int, callback):
		print(host)
		print(port)
		#context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
		context=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)
		context.check_hostname=False
		context.verify_mode=ssl.CERT_NONE
		#print(context.minimum_version, context.maximum_version)
		#print(dir(context))
		context.minimum_version=ssl.TLSVersion.TLSv1_2
		context.maximum_version=ssl.TLSVersion.TLSv1_3
		with socket.create_connection((host,port)) as sock:
			print("create connection")
			with context.wrap_socket(sock, server_hostname=host) as ssock:
				print(ssock.version())
				#TODO watch out for socket.herror, socket.gaierror and socket.timeout
				ssock.connect((host,port))
				return callback(ssock)

class gemini(Protocols):
	def Get(host: str, user=None, port=None, path=None, q=None, frag=None):
		header="gemini://"+host
		#TODO make sure using ipv6 with custom port works
		if port is None:
			port=1985
		else:
			header+=":"+port
		if not path is None:
			header+="/"+path
		if not q is None:
			header+="?"+q
		header=header.encode("utf-8")+b"\r\n"
		def cb(s):
			mime=""
			body=""
			s.sendall(header)
			r= b""
			a=s.recv(1024)#TODO add exception handling
			while(a !=b""):
				r+=a
				a=s.recv(1024)
			#if r==b"":
			#TODO
			r=[x.removesuffix(b"\r") for x in r.split(b"\n")]
			statusdigit1=r[0][0]-b"0"[0]
			statusdigit2=r[0][1]-b"0"[0]
			if statusdigit1==1:
				#TODO input
				pass
			elif statusdigit1==2:
				#success
				mime=r[0][2:].decode()
				#TODO refactor decoding into it's own function
				body=[x.decode() for x in r[1:]]#TODO support other mime types and non-utf8 encodings
			else:
				pass #TODO
			return body
		return Protocols.CreateTLS(host,port, cb)

for x in gemini.Get("namno.duckdns.org", path="blog/"):
	print(x)
root=tk.Tk()
root.geometry("400x250")
#label=tk.Label(root, text="Sample Text")
text1=tk.Text(root, wrap='word', borderwidth=0)
text1.insert('end', 'sampletext')
text1["state"]="disabled"
text1.pack(pady=0)
root.mainloop()
