<?php
/**
 * Created by PhpStorm.
 * User: enured
 * Date: 01/05/24
 * Time: 4:00 PM
 */

namespace IMATHUZH\Qfq\Api;

require_once(__DIR__ . '/../../vendor/autoload.php');

use IMATHUZH\Qfq\Core\Exception\GenericException;
use IMATHUZH\Qfq\Core\Form\Chat;
use IMATHUZH\Qfq\Core\Helper\Logger;
use IMATHUZH\Qfq\Core\Helper\Path;
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\Store\Config;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;


/**
 * Websocket server connection
 *
 */

// Detect API calls if this is defined. Do not try use "const QFQ_API 'Api call'" in Constanst.php : this will break detection of API Calls
define('QFQ_API', 'Api call');

$answer = array();

$logFile = Path::absoluteWebsocketLogFile();
$timestamp = date("Y-m-d H:i:s");

// Define a port number
$configuredPort = Config::get(SYSTEM_WEBSOCKET_PORT) ?? '';
define('PORT', $configuredPort);

if (empty($configuredPort)) {
    Logger::logMessage($timestamp . " - No port defined. Websocket server can not be started. Set the port in QFQ config and restart docker.", $logFile);
}

try {
    $chat = new Chat();
    // Chat class should implement Ratchet\MessageComponentInterface
    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                $chat
            )
        ),
        PORT
    );

    Logger::logMessage($timestamp . " - Port: " . $configuredPort . ". Websocket server started!", $logFile);
    $server->run();

} catch (\Throwable $e) {
    $wrapped = Support::wrapUnexpectedException($e);
    $answer[API_STATUS] = API_ANSWER_STATUS_ERROR;
    try {
        $answer[API_MESSAGE] = $wrapped->formatException();
    } catch (\Throwable $exception) {
        $answer[API_MESSAGE] = 'An unexpected error occurred.';
    }
}

header("Content-Type: application/json");
echo json_encode($answer);

