from . import WebRequestHandler, PathMapping

from ..oms import Oms

class WebServer():

	def __init__(self, endpoint, oms : Oms):
		"""
		Initializes a new instance of the Mocha User Interface Service.
		`endpoint` is a tuple consisting of (str address, int port)
		"""
		self.__tup = endpoint
		self._oms = oms
		self.path_mappings = [ ]
		self.assets = [ ]

	def match_path_pattern(self, source_pattern, path_format):
		vars = [ ]

		if source_pattern == path_format:
			return (True, vars)
		
		# TODO: add intelligent path parsing from PHP/Phast
		# from framework.web import WebPathParser... (e.g.)
		return (False, vars)

	def find_path_mapping(self, path_format : str):
		for mapping in self.path_mappings:
			(success, vars) = self.match_path_pattern(mapping.source_pattern, path_format)
			if success:
				for varname in vars:
					mapping.set_property_value(varname, vars[varname])
				return mapping
		return None

	def serve_forever(self):
		from http.server import HTTPServer

		server = HTTPServer(self.__tup, WebRequestHandler)
		server._oms = self._oms
		server._server = self
		server.serve_forever()