<?php

namespace App\Console\Commands;

use GatewayWorker\BusinessWorker;
use Illuminate\Console\Command;
use Workerman\Worker;
use Workerman\Lib\Timer;
use GatewayWorker\Gateway;
use GatewayWorker\Register;

class GatewayWorkerServer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'worker:server {action} {--daemon}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Start a Worker Server.';

    /**
     * constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        global $argv;

        if (!in_array($action = $this->argument('action'), ['start', 'stop', 'restart','reload'])) {
            $this->error('Error Arguments');
            exit;
        }

        $argv[0] = 'worker:server';
        $argv[1] = $action;
        $argv[2] = $this->option('daemon') ? '-d' : '';

        $this->start();
    }

    private function start()
    {
        $this->startGateWay();
        $this->startBusinessWorker();
        $this->startRegister();
        Worker::runAll();
    }

    private function startBusinessWorker()
    {
        $worker                  = new BusinessWorker();
        $worker->name            = 'YmPayBusinessWorker';                        #设置BusinessWorker进程的名称
        $worker->count           = 4;                                       #设置BusinessWorker进程的数量
        $worker->registerAddress = '127.0.0.1:1239';                        #注册服务地址
        $worker->eventHandler    = \App\Socket\Events::class;   
    }

    private function startGateWay()
    {
        $gateway = new Gateway("websocket://0.0.0.0:9292");
        $gateway->name                 = 'YmPayGateway';                        
        $gateway->count                = 4;                                 #进程的数量
        $gateway->pingInterval = 55;                                        #心跳间隔                   
        $gateway->pingNotResponseLimit = 1;                                 #0为端允许客户端不发送心跳
        $gateway->pingData = '{"type":"websocket"}';                                #检测心跳数据
        $gateway->lanIp                = '127.0.0.1';                       
        $gateway->startPort            = 2300;                              
        $gateway->registerAddress      = '127.0.0.1:1239';                 
    }

    private function startRegister()
    {
        new Register('text://0.0.0.0:1239');
    }

}