#!package export Controller

#!import fs
#!import dirname from path

#!import pathToRegexp from tools.pathToRegexp

class Controller



	middleware: (@config, @globals) ->
		self = @
		controller_root = "#{@globals['root']}/controller"
		controller_setup = @globals['controller'] = {
			lists: {}
			routes: []
			sockets: []
		}
		controller_events = {}

		enumerate_controller = (controller_root, controller, controller_name) ->
			try
				delete require.cache[fullPathController = require.resolve("#{controller_root}/#{controller}/#{controller_name}")]

				fullPath = require.resolve("#{controller_root}/#{controller}/#{controller_name}")
				unless controller_events[fullPath]?
					controller_events[fullPath] = true
					self.config.on fullPath, ->
						enumerate_controller(controller_root, controller, controller_name)

				controller_object = require("#{controller_root}/#{controller}/#{controller_name}")
				for i, v of controller_object
					controller_object = v
					break;

				for func_name, func of controller_object.prototype ? {} when func_name isnt 'constructor'
					tmp_target = 'routes'
					tmp_raw = []

					if func.socket?
						tmp_raw = func.socket.path
						tmp_target = 'sockets'
					else if func.route?
						func.route.dirname = "#{controller_root}/#{controller}"
						for path in func.route.path ? []
							tmp_raw.push
								re: path[0]
								option: {
									controller: controller_name
									action: func_name
									content_type: path[1]
								}
								method: func.route.method
					else
						func.route = {
							dirname: "#{controller_root}/#{controller}"
						}
						tmp_raw.push
							re: pathToRegexp("/#{controller_name}/#{func_name}")
							option: {
								controller: controller_name
								action: func_name
							}
							method: []

					if (c_location = controller_setup[tmp_target].indexOf("#{controller}:#{func_name}")) isnt -1
						controller_setup[tmp_target][c_location] = "#{controller}:#{func_name}"
						controller_setup[tmp_target][c_location+1] = fullPathController
						controller_setup[tmp_target][c_location+2] = tmp_raw
					else
						controller_setup[tmp_target].unshift tmp_raw
						controller_setup[tmp_target].unshift fullPathController
						controller_setup[tmp_target].unshift "#{controller}:#{func_name}"

				old_controller = controller_setup.lists[controller_name] ? null

				controller_setup.lists[controller_name] = new controller_object

				if old_controller? and old_controller.event?
					old_controller.event.emit?('dispose', controller_setup.lists[controller_name])
					for i, v of old_controller.event._events
						old_controller.event.removeAllListeners?(i, v)
					old_controller.event = null

				# console.log(JSON.stringify(controller_setup, null, 4));
			catch
				if _error?.code isnt 'MODULE_NOT_FOUND'
					throw _error
				else
					console.log _error

		@globals.watch.on 'fileChanged', (fileDetail, changes) ->
			if match = /^controller\/(.*)Controller\/(.*)$/g.exec fileDetail.fullPath.replace("#{self.globals.root}/", '')
				update_controller = ->
					controller_name = match[1].toLowerCase()
					enumerate_controller(controller_root, "#{match[1]}Controller", controller_name)
				if /\/models$/g.test fileDetail.directory
					self.config.emit fileDetail.directory, fileDetail, update_controller
				else
					do update_controller
			else if match = /^config\/(.*)/g.exec fileDetail.fullPath.replace("#{self.globals.root}/", '')
				self.config.emit 'update-config', match
			else if /\/models$/g.test fileDetail.directory
				self.config.emit fileDetail.directory, fileDetail, ->


		@globals.watch.on 'fileRemoved', (filePath) ->
			splitted_path = filePath.split '/'
			if splitted_path[-2..][0] is 'components' and /\.ts$/g.test(splitted_path[-1..][0]) and /Controller$/g.test(splitted_path[-3..][0])
				self.config.emit 'components-delete', "/#{splitted_path[-3..][0].replace(/Controller$/g, '').toLowerCase()}/components/#{splitted_path[-1..][0]}"

			if match = /controller\/(.*)Controller\/([a-zA-Z0-9\.]+?)$/g.exec filePath.replace("#{self.globals.root}/", '')
				if (c_location = controller_setup.routes.indexOf(filePath)) isnt -1
					controller_setup.routes.splice(c_location-1, c_location+2)
			else if match = /^config\/(.*)/g.exec filePath.replace("#{self.globals.root}/", '')
				self.config.emit 'delete-config', match

		@globals.watch.on 'fileAdded', (fileDetail) ->
			splitted_path = fileDetail.fullPath.split '/'
			if splitted_path[-2..][0] is 'components' and /\.ts$/g.test(splitted_path[-1..][0]) and /Controller$/g.test(splitted_path[-3..][0])
				self.config.emit 'components-added', ["/#{splitted_path[-3..][0].replace(/Controller$/g, '').toLowerCase()}/components/#{splitted_path[-1..][0]}", fileDetail.fullPath]

			if match = /^controller\/(.*)Controller\/(.*)$/g.exec fileDetail.fullPath.replace("#{self.globals.root}/", '')
				update_controller = ->
					controller_name = match[1].toLowerCase()
					enumerate_controller(controller_root, "#{match[1]}Controller", controller_name)
				if /\/models$/g.test fileDetail.directory
					self.config.emit fileDetail.directory, fileDetail, update_controller
				else
					do update_controller
			else if match = /^config\/(.*)/g.exec fileDetail.fullPath.replace("#{self.globals.root}/", '')
				self.config.emit 'add-config', match
			else if /\/models$/g.test fileDetail.directory
				self.config.emit fileDetail.directory, fileDetail, ->

		if fs.existsSync controller_root
			controller_dirs = fs.readdirSync controller_root
			for controller in controller_dirs
				controller_name = controller.replace(/Controller$/g, '').toLowerCase()
				enumerate_controller(controller_root, controller, controller_name)

		(req, res, app) ->
			# console.log controller_root
			res.set 'Server', "NT Arc-Engine v#{require("#{__dirname}/../package.json").version}"
