<?php
namespace EasyChat;

 
Class Router {

	private $registry;
	private $path;
	private $args = array();
	private $forcedRoute = null;

	 
	function __construct($registry) {
		$this->registry = $registry;
	}

	 
	function setPath($path) {
        $path = $path;
        $path .= DS;
		 
        if (is_dir($path) == false) {
			throw new Exception ('Invalid controller path: `' . $path . '`');
        }
        $this->path = $path;
	}

     
    function setRoute($route) {
        $this->forcedRoute = trim((string)$route, '/\\');
    }
	
	
	function start() {
         
        $this->getController($file, $controller, $action, $args);
		
         
        if (is_readable($file) == false) {
			die ('404 Not Found');
        }
		
         
        include ($file);

         
        $camelized = str_replace(' ', '', ucwords(str_replace('_', ' ', $controller)));
        $class = 'EasyChat\\Controller\\' . $camelized;

        if (!class_exists($class, false)) {
             
            $class = 'Controller_' . $controller;
        }

        $instance = new $class($this->registry);

         
        if (is_callable(array($instance, $action)) == false) {
			die ('404 Not Found');
        }

         
        $instance->$action();
	}
	
		 
		private function getController(&$file, &$controller, &$action, &$args) {
        if ($this->forcedRoute !== null) {
            $route = $this->forcedRoute;
        } else {
            $route = (empty(\EasyChat\Library\RequestContext::get()['route'])) ? '' : \EasyChat\Library\RequestContext::get()['route'];
            unset(\EasyChat\Library\RequestContext::get()['route']);
        }
        if (empty($route)) {
			$route = 'index'; 
		}
		
		 
		 
		 
		$route = trim((string)$route, '/\\');
		$parts = explode('/', $route);
		foreach ($parts as $part) {
			if (!$this->isRoutePartAllowed($part)) {
				die('404 Not Found');
			}
		}

         
        $cmd_path = $this->path;
        foreach ($parts as $part) {
			$fullpath = $cmd_path . $part;

			 
			if (is_dir($fullpath)) {
				$cmd_path .= $part . DS;
				array_shift($parts);
				continue;
			}

			 
			if (is_file($fullpath . '.php')) {
				$controller = $part;
				array_shift($parts);
				break;
			}
        }

		 
        if (empty($controller)) {
			$controller = 'index'; 
		}

         
        $action = array_shift($parts);
        if (empty($action)) { 
			$action = 'index'; 
		}

		$file = $cmd_path . $controller . '.php';
		$args = $parts;
	}

	



	private function isRoutePartAllowed($part) {
		return is_string($part) && preg_match('/^[A-Za-z][A-Za-z0-9_]{0,63}$/D', $part) === 1;
	}
}
