from ...oms.memory import MemoryOms
from ..WebServer import WebServer

from ..AssetLocation import LocalAssetLocation, RemoteAssetLocation
from ..PathMapping import PathMapping

class ServerManager:

	def __init__(self):
		self._servers = [ ]

	def add_server_config(self, filename):
		import yaml

		with open(filename, 'r') as file:
			content = yaml.safe_load_all(file)
			for doc in content:
				for d in doc:
					for s in d["server"]:
						if not "port" in s:
							print("error: 'port' not defined for server definition")
							return

						port = s["port"]
						
						print("[  INFO  ]: running server on port " + str(port))

						oms = MemoryOms()
						svr = WebServer(("127.0.0.1", port), oms)
						
						if "pathMappings" in s:
							pathMappings = s["pathMappings"]
							for pathMapping in pathMappings:
								svr.path_mappings.append(PathMapping(pathMapping["source"], pathMapping["destination"]))
								print("[  INFO  ]: map path '" + pathMapping["destination"] + "' to file path '" + pathMapping["source"] + "'")

						if "assets" in s:
							for asset in s["assets"]:
								
								theAsset = None
								if not "type" in asset:
									print("error: asset location definition does not contain 'type'")
									continue
								elif not "path" in asset:
									print("error: asset location definition does not contain 'path'")
									continue

								if asset["type"] == "local":
									theAsset = LocalAssetLocation()
								elif asset["type"] == "remote":
									theAsset = RemoteAssetLocation()

								if not theAsset is None:
									theAsset.path = asset["path"]
									svr.assets.append(theAsset)
								else:
									print("error: unsupported asset type " + str(asset["type"]))

						print ("loaded assets")
						print(svr.assets)

						if "tenants" in s:
							tenants = s["tenants"]
						else:
							print("warning: no tenants defined in server configuration")

						self._servers.append(svr)

	
	def start(self):
		import threading
		for server in self._servers:
			t = threading.Thread(target = self._serve, args = [ server ])
			t.start()

	def _serve(self, server):
		server.serve_forever()