<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace App\Console\Commands;

use Illuminate\Console\Command;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use Workerman\Worker;
use App\Events\WorkermanEvent;

class Workerman extends Command {
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'work {action} {--d}';

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

	/**
	 * Execute the console command.
	 */
	public function handle() {
		global $argv;
		$action = $this->argument('action');

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

		$this->start();
	}

	public function start() {
        $this->startGateWay();
        $this->startBusinessWorker();
        $this->startRegister();

        $workerPath = storage_path('workerman/');
        if (!is_dir($workerPath))
            mkdir($workerPath, 0755, true);
        Worker::$pidFile = $workerPath . config('app.name') . '_workman.pid';
        $logPath = $workerPath . date('Ym') . '/';
        if (!is_dir($logPath))
            mkdir($logPath, 0755, true);
        Worker::$logFile = $logPath . date('d') . '.log';

        Worker::runAll();
	}

	public function startGateWay() {
		$gateway = new Gateway("websocket://0.0.0.0:2346");
		$gateway->name = 'Gateway';
		$gateway->count = 4;
		$gateway->lanIp = '127.0.0.1';
		$gateway->startPort = 2900;
		$gateway->pingInterval = 10;
		$gateway->pingNotResponseLimit = 1;
		$gateway->pingData = '{"type":"pong"}';
		$gateway->registerAddress = '127.0.0.1:1236';
	}

	public function startBusinessWorker() {
        $worker = new BusinessWorker();
        $worker->name = 'BusinessWorker';
        $worker->count = 3;
        $worker->registerAddress = '127.0.0.1:1236';
        $worker->eventHandler = WorkermanEvent::class;
	}

	public function startRegister() {
		$register = new Register('text://0.0.0.0:1236');
	}
}
