<?php !defined('APP_DIR') ? die('acceess not defined') : '';
class router{
    public $controller = NULL;
    public $method = NULL;
    static public $_instance = NULL;
    
    static public $ctrl;
    static public $mthd;
    
    /**
     * 路由器初始化
     *
     */
    public function __construct(){
        if( defined('FRAME_CONTROLLER') && defined('FRAME_METHOD') ){
            self::$ctrl = $this->controller = FRAME_CONTROLLER;
            self::$mthd = $this->method = FRAME_METHOD;
            return ;
        }
		
        $url = url::current_url();
        $url = str_replace(array('.php','.html','.txt'),array(''),$url);
        $host = url::host();
  
        $url_arr = explode('/',$url);
        array_shift($url_arr);
        if ( empty($url_arr) || empty($url_arr[0]) ) {
            self::$ctrl = $this->controller = 'index';
            self::$mthd = $this->method = 'index';
            return;
        }
        
        $_url_arr  = $url_arr;
        $file_path = '';
        $file_dir  = APP_DIR.'/'.ACTIONS;
        $contr_arr = array();
        do{
            $key = array_shift($_url_arr);
            $file_path = $file_dir.'/'.$key.'.php';
            $file_dir  = $file_dir.'/'.$key;
            if ( file_exists($file_path) ) {
                $contr_arr[] = $key;
                $controller = ACTIONS.'_'.implode('_',$contr_arr);
                $method = empty($_url_arr) ? 'index' : $_url_arr[0];
                if (method_exists($controller, $method)) {
                	self::$ctrl = $this->controller = implode('_',$contr_arr);
                    self::$mthd = $this->method = empty($_url_arr) ? 'index' : $_url_arr[0];
                    break;
                }
            }elseif( file_exists($file_dir) ){
                $contr_arr[] = $key;
            }elseif(method_exists(ACTIONS.'_index', $key)){
                self::$ctrl = $this->controller = 'index';
                self::$mthd = $this->method = $key;
            } else {
                self::$ctrl = $this->controller = 'error_404';
                self::$mthd = $this->method = 'index';
            }
        }while (!empty($_url_arr));
    }
    
    /**
     * 路由器连接
     *
     * @return router
     */
    static public function instance(){
        if (is_null(self::$_instance)) {
            self::$_instance = new router();
            return self::$_instance;
        }else {
            return self::$_instance;
        }
    }
}
?>