1:  2:  3:  4:  5:  6:  7:  8:  9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 
<?php

namespace Manticoresearch\Connection;

use Manticoresearch\Connection;
use Manticoresearch\Connection\Strategy\SelectorInterface;
use Manticoresearch\Exceptions\ConnectionException;
use Manticoresearch\Exceptions\NoMoreNodesException;

/**
 * Class ConnectionPool
 * @package Manticoresearch\Connection
 */
class ConnectionPool
{
    /**
     * @var array
     */
    protected $_connections;

    /**
     * @var SelectorInterface
     */
    public $strategy;

    public $retries;

    public $retries_attempts =0;

    public function __construct(array $connections, SelectorInterface $strategy, int $retries)
    {
        $this->_connections = $connections;
        $this->strategy = $strategy;
        $this->retries = $retries;
    }

    /**
     * @return array
     */
    public function getConnections(): array
    {
        return $this->_connections;
    }

    /**
     * @param array $connections
     */
    public function setConnections(array $connections)
    {
        $this->_connections = $connections;
    }
    public function getConnection(): Connection
    {
        $this->retries_attempts++;
        $connection =   $this->strategy->getConnection($this->_connections);
        if ($connection->isAlive()) {
            return $connection;
        }
        if ($this->retries_attempts < $this->retries) {
            return $connection;
        }
        throw new NoMoreNodesException('No more retries left');
    }

    public function hasConnections(): bool
    {
        return $this->retries_attempts < $this->retries;
    }

    /**
     * @return SelectorInterface
     */
    public function getStrategy(): SelectorInterface
    {
        return $this->strategy;
    }

    /**
     * @param SelectorInterface $strategy
     */
    public function setStrategy(SelectorInterface $strategy)
    {
        $this->strategy = $strategy;
    }
}