<?php
namespace app;
use \app\Route;

class App{
    public static $classMap = array();#用于判断类是否存在，节约性能
 
    /**
     * 运行控制器和方法
     * @throws \Exception
     */
    public static function run()
    {
        $ctrlClass = '\\app\\Index';
        $action = self::getAction();
        $ctrl = new $ctrlClass();
        $ctrl->$action();
    }

    public static function getAction()
    {
        $pathinfo = "";
        if (isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO']) ) {
            $pathinfo = $_SERVER['PATH_INFO'];
        } else {
            $pathinfo = strpos($_SERVER['REQUEST_URI'], '?') ? strstr($_SERVER['REQUEST_URI'], '?', true) : $_SERVER['REQUEST_URI'];
        }


        $action = '';
        $doc = '';

        if ($pathinfo) {
            // $pathArr = explode('/',trim($pathinfo,'/'));//数组
            // if (isset($pathArr[0])){
            //     $action = camelize($pathArr[0]);
            //     unset($pathArr[0]);
            // }
            //url 多余部分转换成GET eg:index/id/1 实现get传值
            // $count = count($pathArr) + 1;

            // $i = 1;
            // while ($i < $count){
            //     if (isset($pathArr[$i+1])){
            //         $_GET[$pathArr[$i]] = $pathArr[$i+1];
            //     }
            //     $i = $i + 2;
            // };
            // foreach ($pathArr as $value) {
            //     $doc .= '/' . $value;
            // }
            // if (isset($pathArr[1])) {
            //     $_GET['doc'] = $pathArr[1];
            // }

            // 提取 action, 多余部分转为 markdown 文件路径
            $pathinfo = ltrim($pathinfo, '/');
            
            if ($index = strpos($pathinfo, '/')) {
                $action = substr($pathinfo,0,$index);
            } else {
                $action = $pathinfo;
            }
            // var_dump($pathinfo);

            $doc = substr($pathinfo, strlen($action));
        }
        $action = $action ? : "index";
        
        $GLOBALS['action'] = $action;
        $GLOBALS['doc'] = $doc;
        
        return $action;
    }
}
