<?php
declare (strict_types = 1);

namespace app\listener;

use freedom\utils\SocketSession;
use think\swoole\WebSocket;

class WsClose
{
    /**
     * 事件监听处理
     *
     * @return void
     */
    public function handle(WebSocket $ws){
        $tableFd = app('swoole.table.fd');
        $fd = $ws->getSender();
        $fdInfo = $tableFd->get((string) $fd);
        $mode = $fdInfo['mode'];
        switch ($mode) {
            case 'space':
                $tableSpace = app('swoole.table.space');
                $tableSpace->del((string) $fdInfo['table_id']);
                $ws->leave(SocketSession::SPACE_ROOM_NAME);
                break;
            case 'scan':
                $tableScan = app('swoole.table.scan');
                $tableScan->del((string) $fdInfo['scan_appid']);
                $ws->leave(SocketSession::SCAN_ROOM_NAME);
                break;
            case 'user':
                $tableUser = app('swoole.table.user');
                $tableUser->del((string) $fdInfo['user_id']);
                $ws->leave(SocketSession::USER_ROOM_NAME);
                break;
            case 'api':
                $tableApi = app('swoole.table.api');
                $tableApi->del((string) $fdInfo['api_appid']);
                $ws->leave(SocketSession::API_ROOM_NAME);
                break;
            case 'manager':
                $tableManager = app('swoole.table.manager');
                $tableManager->del((string) $fdInfo['user_id']);
                $ws->leave(SocketSession::MANAGER_ROOM_NAME);
                break;
            case 'chat_user':
                $chatListener = new \app\listener\chat\ChatConnectListener();
                $chatListener->onClose($ws);
                break;
            case 'chat_agent':
                $chatListener = new \app\listener\chat\ChatConnectListener();
                $chatListener->onClose($ws);
                break;
        }
        $tableFd->del((string) $fd);
        $ws->leave(SocketSession::HOUSE_NAME);
        echo $fd.":退出\n";
    }
}
