<?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\Events;

use GatewayWorker\BusinessWorker;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Log;
use Workerman\Lib\Timer;

class WorkermanEvent {

	/**
	 * @title worker 启动时触发
	 *
	 * @param BusinessWorker $businessWorker
	 * @return void
	 */
	public static function onWorkerStart(BusinessWorker $businessWorker) {

		self::log(__FUNCTION__, $businessWorker->workerId);
		// 向所有客户端连接发送数据
		// Gateway::sendToAll("worker started");
		// 定时向所有客户端连接发送数据
		Timer::add(1, function() use ($businessWorker) {
			$time_now = time();
			foreach ($businessWorker->connections as $connection) {
				if (empty($connection->lastMessageTime)){
					$connection->lastMessageTime = $time_now;
					continue;
				}
				if ($time_now - $connection->lastMessageTime > 10) {
					$connection->lastMessageTime = $time_now;
					Gateway::sendToClient($connection->id, 'pong');
				}
			}
		});
	}

	/**
	 * @title 当客户端连接时触发
	 *
	 * @param int $client_id 连接id
	 * @return void
	 */
	public static function onConnect($client_id) {
		self::log(__FUNCTION__, $client_id);
	}

	/**
	 * @title 客户端连接时触发
	 *
	 * @param int $client_id 连接id
	 * @param mixed $message 具体消息
	 * @return void
	 */
	public static function onWebSocketConnect($client_id, $data) {
		self::log(__FUNCTION__, $client_id, $data);
	}

	/**
	 * @title 当客户端发来消息时触发
	 *
	 * @param int $client_id 连接id
	 * @param mixed $message 具体消息
	 * @return void
	 */
	public static function onMessage(string $client_id, string $message) {
		self::log(__FUNCTION__, $client_id, $message);

		if (empty($message)) {
			return;
		}

		Gateway::sendToAll($message);
		if ($message == 'ping') {
			Gateway::sendToClient($client_id, 'pong');
			return;
		}
	}

	/**
	 * @title 当用户断开连接时触发
	 *
	 * @param int $client_id 连接id
	 * @return void
	 */
	public static function onClose(string $client_id) {
		self::log(__FUNCTION__, $client_id);
		Gateway::destoryClient($client_id);
	}

	protected static function log(string $title, ...$data): void{
		if (config('app.debug')) {
			Log::info("{$title} | " . json_encode($data, 256));
		}
	}
}
