<?php

namespace app\command\admin;

use app\event\SysGatewayEvent;
use GatewayWorker\Register;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use \GatewayWorker\BusinessWorker;
use Workerman\Worker;

class SysGateway extends Command
{
    private string $registerAddress;

    protected function configure()
    {
        $this->setName('admin:gateway')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('mode', 'm', Option::VALUE_OPTIONAL, 'Run the workerman server in daemon mode.')
            ->setDescription('后台系统网关服务');
    }

    protected function execute(Input $input, Output $output)
    {
        $action = $input->getArgument('action');
        $mode = $input->getOption('mode');
        global $argv;
        $argv = [];
        array_unshift($argv, 'think', $action);
        if ($mode == 'd') {
            $argv[] = '-d';
        } else if ($mode == 'g') {
            $argv[] = '-g';
        }

        $this->registerAddress = config('admin.gateway.registerAddress', '127.0.0.1:1236');


        /*
         * 载入注册中心
         */
        $this->startRegister();

        /*
         * 载入网关中心
         */
        $this->startGateway();

        /*
         * 业务处理器
         */
        $worker = new BusinessWorker();
        $worker->name = 'AdminBusinessWorker';
        $worker->count = 4;
        $worker->registerAddress = $this->registerAddress;
        $worker->eventHandler = SysGatewayEvent::class;

        // 运行所有服务
        Worker::runAll();
    }


    private function startRegister(): Register
    {
        return new Register("text://$this->registerAddress");
    }
    private function startGateway(): \GatewayWorker\Gateway
    {
        // gateway 进程
        $gateway = new \GatewayWorker\Gateway('Websocket://'.config('admin.gateway.websocketAddress', '0.0.0.0:19981'));
        // 设置名称，方便status时查看
        $gateway->name = 'AdminGateway';
        // 设置进程数，一般两个进程就足够
        $gateway->count = 2;
        // 分布式部署时请设置成内网ip（非127.0.0.1）
        $gateway->lanIp = '127.0.0.1';
        // 内部通讯起始端口。假如$gateway->count=2，起始端口为2300
        // 则一般会使用2300 2301 2个端口作为内部通讯端口
        $gateway->startPort = (int)config('admin.gateway.startPort', 2300);
        // 心跳间隔
        $gateway->pingInterval = 10;
        // 心跳数据
        $gateway->pingData = '{"type":"ping"}';
        // 服务注册地址
        $gateway->registerAddress = $this->registerAddress;

        /*
        // 当客户端连接上来时，设置连接的onWebSocketConnect，即在websocket握手时的回调
        $gateway->onConnect = function($connection)
        {
            $connection->onWebSocketConnect = function($connection , $http_header)
            {
                // 可以在这里判断连接来源是否合法，不合法就关掉连接
                // $_SERVER['HTTP_ORIGIN']标识来自哪个站点的页面发起的websocket链接
                if($_SERVER['HTTP_ORIGIN'] != 'http://chat.workerman.net')
                {
                    $connection->close();
                }
                // onWebSocketConnect 里面$_GET $_SERVER是可用的
                // var_dump($_GET, $_SERVER);
            };
        };
        */

        return $gateway;
    }
}