<?php

declare(strict_types=1);

namespace core\http2Client;

final class Http2Client
{
    /** @var array<string,Http2Client> */
    private static array $cache = [];

    private \utils\connectiondata\Http2ConnectionData $connectionData;

    private function __construct(\utils\connectiondata\Http2ConnectionData $connectionData)
    {
        $this->connectionData = $connectionData;
    }

    private static function connectionKey(\utils\connectiondata\Http2ConnectionData $connectionData): string
    {
        return $connectionData->toCanonicalKey();
    }

    private static function addOrGetClient(\utils\connectiondata\Http2ConnectionData $connectionData): Http2Client
    {
        $key = self::connectionKey($connectionData);
        if (isset(self::$cache[$key])) {
            return self::$cache[$key];
        }
        return self::$cache[$key] = new Http2Client($connectionData);
    }

    public static function sendMessage(\utils\connectiondata\Http2ConnectionData $connectionData, array $message): array
    {
        self::addOrGetClient($connectionData);
        // TODO: Use framework HTTP/2 client in a later step.
        // Keep this client as skeleton for now.
        return [];
    }

    public static function closeClient(\utils\connectiondata\Http2ConnectionData $connectionData): void
    {
        unset(self::$cache[self::connectionKey($connectionData)]);
    }

    public static function getState(\utils\connectiondata\Http2ConnectionData $connectionData): ?string
    {
        return isset(self::$cache[self::connectionKey($connectionData)]) ? 'OPEN' : null;
    }
}
