<?php

require_once(LIBDIR."/autoloader/autoloader.php");
require_once(LIBDIR."/mvcfronk/mfLog/mfLoghandler.php");

/**
 * This class routes incoming requests. 
 * It should be called by the entry script (public/index.php or CLI.php) as the entrypoint into the application.
 * Looks at mod and action parameters and loads the corresponding class.
 * If no parameters are given, uses default route.
 * Also loads Configfile.
 * 
 * @author fronk
 * @param array of request params $request
 */
class mfRouter {
	private $default=array();
	private $mod;
	private $action;
	
	
	public function __construct($request) {
    // set default route, in case no default route is defined in configfile.
		$this->default['mod']="Application";
		$this->default['action']="Index";
		
    if(!defined('MFUSEFANCYURLS')) {
      define('MFUSEFANCYURLS',false);
    }
    
		if(defined("DEFAULT_ROUTE") && strlen(DEFAULT_ROUTE)) {
			$defroute=explode("_",DEFAULT_ROUTE);
			$this->default['mod']=$defroute[0];
			if($defroute[1]) {
				$this->default['action']=$defroute[1];
			}
			
		}
		
    if(defined("MFSESSION") && MFSESSION === true) {
      session_name(MFAPPNAME."_session");
      session_start();
    }
    
    // set parameters supplied in url
    $umod = "";
    $uaction = "";
    
    // get mod and action
		if(preg_match('/^([^_]+)(?:_(.+)?)?$/',$request['action'],$m)) {
      $umod = $m[1];
			$this->mod=$m[1];
			$this->action="Index";
			if($m[2]) {
        $uaction = $m[2];
				$this->action=$m[2];
			}
		} else {
			$this->mod=$this->default['mod'];
			$this->action=$this->default['action'];
		}
    // get baseurl from fancy urls if used
    if(MFUSEFANCYURLS) {
      if(!$umod) {
        $baseurl = $_SERVER['REQUEST_URI'];
      }
      if($umod && !$uaction) {
        if(preg_match("#^(.+)/$umod/?\\??#",$_SERVER['REQUEST_URI'],$m)) {
          $baseurl = $m[1];
        }
      }
      if($umod && $uaction) {
        if(preg_match("#^(.+)/$umod/$uaction/?\\??#",$_SERVER['REQUEST_URI'],$m)) {
          $baseurl = $m[1];
        }
      }
      define("MFFANCYBASEURL",$baseurl);
    }
    
		$request['mod']=ucfirst($this->mod);
		$request['action']=ucfirst($this->action);
		
    define('MFROUTER_MOD',$this->mod);
    define('MFROUTER_ACTION',$this->action);
    
		// initiate layout instance
		$Layout=Layout::singleton();
		$Layout->setTemplate($this->mod."/".$this->action);
		$Layout->set("Mod",$this->mod);
		$Layout->set("Action",$this->action);
		
		// load the appropriate Controller
		$classname=$this->mod."Controller";
		try {
			$page=new $classname($request);
		} catch(Exception $e) {
			require_once(LIBDIR."/mvcfronk/mfExceptionhandler/mfExceptionhandlerController.php");
			$exhc=new mfExceptionhandlerController($e);
		}
		
		$Layout->display();
	}

}