<?php
/**
 * Created by PhpStorm.
 * User: enured
 * Date: 01/05/24
 * Time: 4:00 PM
 *
 * DEPRECATED: This websocket server requires Ratchet which is no longer included by default.
 * To enable: cd extension && composer require cboden/ratchet:0.4.3
 * This will be removed when nchan migration is complete.
 */

namespace IMATHUZH\Qfq\Api;

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

use IMATHUZH\Qfq\Core\Form\ChatRatchet;
use IMATHUZH\Qfq\Core\Helper\Logger;
use IMATHUZH\Qfq\Core\Helper\Path;
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\Store\Config;


/**
 * Websocket server connection (requires Ratchet)
 *
 */

// 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");

// Check if Ratchet is available
if (!class_exists('Ratchet\Server\IoServer')) {
    $errorMsg = "Ratchet is not installed. To enable the websocket server, run: cd extension && composer require cboden/ratchet:0.4.3";
    Logger::logMessage($timestamp . " - " . $errorMsg, $logFile);
    $answer[API_STATUS] = API_ANSWER_STATUS_ERROR;
    $answer[API_MESSAGE] = $errorMsg;
    header("Content-Type: application/json");
    echo json_encode($answer);
    exit(1);
}

// Check if ChatRatchet class is available
if (!class_exists('IMATHUZH\Qfq\Core\Form\ChatRatchet')) {
    $errorMsg = "ChatRatchet class not available. Ratchet may not be properly installed.";
    Logger::logMessage($timestamp . " - " . $errorMsg, $logFile);
    $answer[API_STATUS] = API_ANSWER_STATUS_ERROR;
    $answer[API_MESSAGE] = $errorMsg;
    header("Content-Type: application/json");
    echo json_encode($answer);
    exit(1);
}

// 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 ChatRatchet();
    // ChatRatchet class implements Ratchet\MessageComponentInterface
    $server = \Ratchet\Server\IoServer::factory(
        new \Ratchet\Http\HttpServer(
            new \Ratchet\WebSocket\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);

