<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/21
 * Time: 16:03
 */

namespace app\logic;

///composer update或者composer install或者composer dump-autoload.
///

use app\lib\DataPack;

use  app\logic\cmdpro\CmdTest as CmdTest;
use  app\logic\cmdpro\CmdQuery as CmdQuery;
use  app\logic\cmdpro\CmdLogin as CmdLogin;
use  app\logic\cmdpro\CmdSubser as CmdSubser;


class CmdProxy
{
    private static $Instance = null;

    public static function getInstance($cache = true)
    {
        if ($cache && self::$Instance) {
            echo "直接返回 CmdProxy OBJ\n";
            return self::$Instance;
        }
        echo "新建 CmdProxy OBJ\n";
        self::$Instance = new self();
        return self::$Instance;
    }

    public function ParaCMD($serv, \Swoole\Server\Task $task)
    {

        $fd = $task->data->fd;
        $dataPack = json_decode(trim($task->data->data),true);
        $cmd = isset($dataPack['cmd']) ? $dataPack['cmd'] : '';
        $cmdcls = $this->getParaCmd($cmd);

        if (!$cmdcls) {
            $serv->push($fd, DataPack::toJson(['mt' => 'errorMsg', 'data' => 'error cmd!']));
            $serv->disconnect($fd);
            return;
        }
        $cmdObj = $this->getClsObj($cmdcls);
        try{
            $cmdObj->paraCmd($serv, $task);
        }catch (\Exception $e){

        }
        unset($cmdObj) ;
    }

    public function  getClsObj($cmd)
    {
        $obj = null ;
        switch ($cmd){
            case "CmdTest":
                $obj = new CmdTest();
                break ;
            case "CmdQuery":
                $obj = new CmdQuery();
                break;
            case "CmdLogin":
                $obj = new CmdLogin();
                break;
            case "CmdSubser":
                $obj = new CmdSubser();
                break;
            default:
                break;
        }
        return $obj ;
    }


    public function allCmdMaps()
    {
        $arrs = [
            'login' => 'CmdLogin',
            'query' => 'CmdQuery',
            'test' => 'CmdTest',
            'subserv' => 'CmdSubser',
        ];
        return $arrs;
    }

    public function getParaCmd($cmd)
    {
        $arr = $this->allCmdMaps();
        if (isset($arr[$cmd])) {
           return $arr[$cmd];
        }
       return false;
    }


}