<?php
/**
 * Router
 *
 * @author Milan Lempera
 * @package Classes
 * @copyright Web-systems.cz  2009
 *
 */

class Router {

  /**
   * @var cesta ke kontroleru
   */
  private $path;

  /**
   * @var parametry předané kontroleru
   */
  private $args = array();

  /**
   * @var název controlleru
   */
  private $controller;

  /**
   * @var název stránky
   */
  private $page;

  /**
   * @var akce controlleru
   */
  private $action;

  /**
   * @var instance uložiště
   */
  private $registry;

  public function __construct() {
    $this->registry = Registry::getInstance();
  }

  /**
   * Nastavení cesty ke kontroleru
   * @var instance registru
   */
  public function setPath($path) {
    $path = trim($path, '/\\');
    $args = explode('/',$path);
    $this->registry->argsBack = $args;

    Debug::addPoint('$path: ',$path);
    Debug::addPoint('$args: ',$args);

    /*	Není poteřba rozlišovat jazyky
     if ( strlen($args[0]) == 2 ) {
     $language = $args[0];
     unset($args[0]);
     $args = Tools::arrayRecount($args);
     }
     else{
     $language = __DEFAULT_LANG;
     }

     if ( $this->registry->multilanguage == true ) {
     $this->registry->language = $language;
     }
     */
    if ( !empty($args[0]) ) {
      if ( ereg('^([a-zA-Z0-9_]+)(_)$', $args[0], $page) ) {
        $this->controller = 'stranka';
        $this->action     = 'index';
        $this->args       = $page[1];
      }
      elseif ( ereg('^(_)([a-zA-Z0-9_]+)', $args[0], $page) ) {
        $this->controller = 'subsite';
        $this->action     = 'zobrazit';
        $this->args       = $page[2];
      }
      elseif ( substr($args[0],0,9) == 'kategorie') {
      	$this->controller = 'kategorie';
        $this->action     = 'zobrazit';
      }
      elseif ( substr($args[0],0,7) == 'produkt') {
      	$this->controller = 'produkt';
        $this->action     = 'zobrazit';
      }
      else {
        $sadmin = substr($args[0],0,5);
        if ($sadmin == 'admin') {
          $this->registry->admin = true;
          if ( $this->registry->user->login ) {
            Debug::addPoint('Login - OK');
          }
          else {
            if (@$args[0] != 'admin' AND @$args[1] != 'prihlasit') {
              $this->registry->addPersistent('next_request',$args,9);
              $this->registry->addPersistent('next_post',$_POST,9); // 2 - přihlášení + redirect
              unset($args);
              $args = array();
            }
            $args[0] = 'admin';
            $args[1] = 'prihlasit';
          }

          /*unset($args[0]);
           //Tools::arrayRecount($args);
           if (!empty($args[0]) ) {
           $args[0] = 'admin'.$args[0];
           }
           else {
           $args[0] = 'admin';
           }
           */
        }
        $this->controller = $args[0];
        if (!empty($args[1]) ) {
          $this->action = $args[1];
          unset($args[1]);
        }
        else {
          $this->action = 'index';
        }
      }

      $this->registry->postRestore = false;
      if (isset($this->registry->next_post) AND count($_POST) == 0) {
        $_POST = $this->registry->next_post;
        $this->registry->postRestore = true;
        if (isset($this->registry->message)) {
          $this->registry->message .= '<br /> &rarr byla obnovena data z předchozího požadavku.';
        }
        unset($this->registry->next_post);
      }

      unset($args[0]);
      if (!empty($this->args)) {
        $this->args = array_merge( array($this->args), Tools::arrayRecount($args));
      }
      else {
        $this->args = Tools::arrayRecount($args);
      }
    }
    else {
      $this->controller = DEFAULT_CONTROLLER;
      $this->action = DEFAULT_CONTROLLER_ACTION;
    }
    /*
     if ( !empty($args[0]) ) {
     if ( ereg('^([a-zA-Z0-9_]+)(_)$', $args[0], $page) ) {
     $this->controller = 'stranka';
     $args[1]       = $page[1];
     }
     elseif ( ereg('^(_)([a-zA-Z0-9_]+)', $args[0], $page) ) {
     $this->controller = 'subsite';
     $this->page       = $page[2];
     }
     else {
     //die('ddd'.$args[0]);
     $this->controller = $args[0];
     }
     }
     else {
     $this->controller = 'index';
     }
      
     if ( !empty($args[1]) ) {
     $this->action = $args[1];
     }
     else {
     $this->action = 'index';
     }
     */
    try {

      $controller_name = 'controllers' . DIRSEP . $this->controller . 'Controller.php';
      if ( is_readable($controller_name) == false) {
				$url = $this->controller.'/'.$this->action.'/'.@implode(DIRSEP,@$this->args);
        $log_id = Logger::errorAll( 6, $this->controller, $this->action, $this->args, 'Soubor Controlleru nelze číst.');
      	if ($this->registry->admin) {
      		$this->controller = 'adminerror';
      	}
      	else {
      		$this->controller = 'error';
      	}
        $this->action	= 'index';
        $this->args		= array(404,@$log_id);
      }

		}
		catch(Appliexception $e){
    	if ($e->level <= 3) {
    		$this->registry->html_view = excHandler($e);

    		
    	}
    }
    
    $this->checkURLAction($args);

    $ret = array();
    $ret['controller'] = strtolower($this->controller);
    $ret['name']       = $ret['controller'] . 'Controller';
    $ret['action']    = strtolower($this->action);
    $ret['args']      = $this->args;
    $ret['URL']       = $ret['controller'].'/'.$ret['action'].'/'.@implode(DIRSEP,@$ret['args']);

    return $ret;

  }

  private function checkURLAction(& $args) {

  	$this->registry->form_send = false;
  	$this->registry->page_view = false;
  	if (count($args) > 0) {
// kontrola odeslání formuláře
    	$send = array_search(SEND, $args);
      if ($send !== false) {
        $this->registry->form_send = true;
        unset($send);
      }

// kontrola požadavka na pohled
      $view = array_search(VIEW, $args);
      if ($view !== false) {
        $this->registry->page_view = true;
        unset($view);
      }

// kontrola požadavka na řazení
      $order = array_search(ORDER, $args);
      if ($order !== false) {
      	$my_order = array();
        $m = count($args)+$order;
        unset($args[$order]);
        for($i = $order+1; $i < $m; $i++) {
        	if (isset($args[$i])) {
          	$a = $args[$i];
          	if (substr($a,0,1) == '-'){
          		$item['name'] = substr($a,1);
          		$item['ord']  = 'DESC';
          	}
          	else {
          		$item['name'] = $a;
          		$item['ord']  = 'ASC';
          	}
          	if ($a == ORDER_END) {
          		unset($args[$i]);
          		break;
          	}
          	$my_order[] = $item;
          	unset($args[$i]);
  
            
        	}
        }
        $this->registry->content_order = $my_order;
      }
      
      $args = Tools::arrayRecount($args);
  	}
  }

}
?>