<?php


namespace Mainto\RpcServer\RpcClient;


use RuntimeException;

class RpcClientFactory {
    public static array $clients = [];

    public static function getClient(string $network, string $serviceName): RpcClient {
        if(!isset(self::$clients[$network][$serviceName])) {
            self::$clients[$network][$serviceName] = self::newClient($network, $serviceName);
        }

        return self::$clients[$network][$serviceName];
    }

    private static function newClient(string $network, string $serviceName) {
        switch ($network) {
            case "unix":
                return RpcClient::getServiceClient($serviceName);
        }

        throw new RuntimeException("not support client: ". $network);
    }

    public static function clearClient(string $network, string $serviceName) {
        if(isset(self::$clients[$network][$serviceName])) {
            /** @var RpcClient $client */
            $client = self::$clients[$network][$serviceName];
            $client->close();
            unset(self::$clients[$network][$serviceName]);
        }
    }
}
