extends Control

const mime_types: Dictionary = {
		"html": "text/html",
		"htm": "text/html",
		"md": "text/plain",
		"css": "text/css",
		"txt": "text/plain",
		"png": "image/png",
		"jpg": "image/jpeg",
		"jpeg": "image/jpeg",
	}

var _server: HTTPServer = null

var files: Array = []


func _ready() -> void:
	_start_server()


func _start_server(port: int = 3001) -> void:
	if _server:
		return

	_server = HTTPServer.new()
	var dir := Directory.new()
	if dir.open("res://server_files") == OK:
		dir.list_dir_begin()
		var file_name := dir.get_next()
		while file_name != "":
			if !dir.current_is_dir():
				if file_name.get_extension() == "import":
					file_name = dir.get_next()
					continue

				print(file_name)

				_server.endpoint(HTTPServer.Method.GET, "/%s" % file_name, funcref(self, "_serve_file"), [file_name])

			file_name = dir.get_next()

		_server.endpoint(HTTPServer.Method.GET, "/", funcref(self, "_serve_file"), ["index.html"])


	_server.listen(port)


func _stop_server() -> void:
	if _server:
		_server = null


func _process(_delta: float) -> void:
	if _server == null:
		return

	_server.take_connection()


func _serve_file(request: HTTPServer.Request, response: HTTPServer.Response, binds: Array) -> void:
	var file_name: String = binds[0] as String
	print(file_name)

	var f = File.new()
	f.open("res://server_files/%s" % file_name, File.READ)

	var mime = get_mime_type(file_name)

	response.header("content-type", get_mime_type(file_name))

	response.data(f.get_as_text())
#	else:
#		response.header("content-type", "text/plain")
#		response.data("500 - Read Error")


func get_mime_type(file_name: String) -> String:
	var ext := file_name.get_extension().to_lower()
	return mime_types[ext] if ext in mime_types else "application/octet-stream"
