<?php


namespace app\listener\chat;

use app\services\chat\SessionService;
use think\swoole\WebSocket;

/**
 * 聊天心跳监听器
 * 处理: chat.ping 事件
 */
class ChatPing
{
    private $sessionService;

    public function __construct()
    {
        $this->sessionService = new SessionService();
    }

    /**
     * 事件监听处理
     */
    public function handle(array $event, WebSocket $ws)
    {
        $fd = $ws->getSender();
        $tableFd = app('swoole.table.fd');
        $fdInfo = $tableFd->get((string)$fd);

        if (!$fdInfo) {
            return;
        }

        if ($fdInfo['mode'] === 'chat_user') {
            $this->sessionService->refreshUserConnection($fdInfo['user_id']);
        } elseif ($fdInfo['mode'] === 'chat_agent') {
            $this->sessionService->refreshAgentConnection($fdInfo['user_id']);
        }

        $ws->emit('chat_pong', []);
    }
}
