<?php


namespace Mainto\RpcServer\RpcServer\Connection;


use Mainto\RpcServer\RpcServer\BaseRpcConnection;
use Mainto\RpcServer\RpcServer\ConnectionHandler;
use Mainto\RpcServer\Util\Net\Net;
use Throwable;

class RpcUnixConnection extends BaseRpcConnection {
    /**
     * RpcUnixConnection constructor.
     * @param $address
     * @param ConnectionHandler $handler
     */
    private function __construct ($address, ConnectionHandler $handler) {
        parent::__construct(Net::dial("unix", $address), $address, $handler);
    }

    public static function tryNewInstance ($address, ConnectionHandler $handler) {
        return new self($address, $handler);
    }

    /**
     * @param $address
     * @param ConnectionHandler $handler
     * @param $second
     * @return RpcUnixConnection
     * @throws Throwable
     */
    public static function mustNewInstance ($address, ConnectionHandler $handler, $second) {
        $times = $second / 0.3;
        $i = 0;
        while (true) {
            try {
                return self::tryNewInstance($address, $handler);
            } catch (Throwable $exception) {
                if ($i++ > $times) {
                    throw $exception;
                }
                usleep(1000 * 300);
            }
        }
    }
}