<?php

// 加载全局的自动加载文件
require_once '/root/.composer/vendor/autoload.php';

// 加载本地的自动加载文件
require_once __DIR__ . '/vendor/autoload.php';


use Workerman\Worker;


// 创建一个 Websocket server
$ws_worker = new Worker('websocket://0.0.0.0:2346');
$ws_worker->onConnect = 'onWebSocketConnect';
$ws_worker->onMessage = 'onWebSocketMessage';
$ws_worker->onClose = 'onWebSocketClose';
$ws_worker->onWorkerStop = 'onWorkerStopping';


function onWebSocketConnect($connection)
{
    echo "New connection\n";
}

function onWebSocketMessage($connection, $data)
{
    $request = json_decode($data, true);

    if (isset($request['action'])) {
        $action = $request['action'];
        $className = '\app\actions\\' . ($action);

        if (class_exists($className)) {
            $instance = new $className();
            $param = $request['param'] ?? [];
            $response = $instance->handle($param);
            $connection->send(json_encode($response));
        } else {
            $connection->send(json_encode(['error' => 'Class not found']));
        }
    } else {
        $connection->send(json_encode(['error' => 'Invalid request']));
    }
}

function onWebSocketClose($connection)
{
    echo "Connection closed\n";
}

function onWorkerStopping()
{
    echo "\nWorker is stopping...\n";


}

Worker::runAll();