<?php
namespace app;

use app\utils\Str;

class Request
{
    /**
     * 请求方法是否为Post
     * @var bool
     */
    protected $isPost = false;

    /**
     * 控制器名
     * @var string
     */
    public $controller;

    /**
     * 操作名
     * @var string
     */
    public $actionName;

    /**
     * 参数
     * @var array
     */
    public $params;

    /**
     * 初始化
     * @var bool
     */
    protected static $initialized = false;

    //创建静态私有的变量保存该类对象
    private static $instance;

    //防止直接创建对象
    private function __construct(){
        
    }

    public static function getInstance($initforce = false){
        //判断$instance是否是APP的对象 没有则创建
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }

        // 判断是否强制初始化及是否未初始化
        if ($initforce || !self::$initialized) {
            self::$instance->init();
        }

        return self::$instance;
    }

    public function init()
    {
        self::$initialized = true;

        if ($_SERVER['REQUEST_METHOD'] == 'POST') { 
            $this->isPost = true;
        }

        $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'];
        }

        if (is_string($pathinfo)) {
            $result = explode('/', trim($pathinfo,'/'));
        }

        // 获取控制器名
        // $controller = strip_tags($result[0] ?: 'Index');

        // $this->controller = camelize($controller);
        
        // 获取操作名
        // $this->actionName = strip_tags(isset($result[1]) ? $result[1] : 'index');
        
        // 控制器名只用 Index
        $this->controller = "Index";

        $this->actionName = strip_tags(isset($result[0]) && !empty($result[0]) ? $result[0] : 'index');

        // 文档路径
        $doc = '';
        if (count($result) > 1) 
        {
            for ($i = 1; $i < count($result); $i++) {
                $doc .= '/' . $result[$i];
            }
        }

        $this->params = array_merge($_GET, $_POST, ['doc'=>$doc]);

        return $this;
    }

    /**
     * 是否初始化过
     * @return bool
     */
    public function initialized()
    {
        return $this->initialized;
    }

    public function isPost()
    {
        return $this->isPost;
    }
}
