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:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 
<?php

declare(strict_types=1);

namespace Manticoresearch;

use Manticoresearch\Connection\ConnectionPool;
use Manticoresearch\Connection\Strategy\SelectorInterface;
use Manticoresearch\Connection\Strategy\StaticRoundRobin;

use Manticoresearch\Endpoints\Pq;
use Manticoresearch\Exceptions\ConnectionException;
use Manticoresearch\Exceptions\NoMoreNodesException;
use Manticoresearch\Exceptions\RuntimeException;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
 * Manticore  client object
 * @package Manticoresearch
 * @category Manticoresearch
 * @author Adrian Nuta <adrian.nuta@manticoresearch.com>
 * @link https://manticoresearch.com
 */
class Client
{
    /**
     *
     */
    const VERSION = '1.0.0';

    /**
     * @var array
     */
    protected $_config = [];
    /**
     * @var string
     */
    private $_connectionStrategy = StaticRoundRobin::class;
    /**
     * @var ConnectionPool
     */
    protected $_connectionPool;

    /**
     * @var LoggerInterface|NullLogger
     */
    protected $_logger;

    protected $_lastResponse;

    /*
     * $config can be a connection array or
     * $config['connections] = array of connections
     * $config['connectionStrategy'] = class name of pool strategy
     */
    public function __construct($config = [], LoggerInterface $logger = null)
    {
        $this->setConfig($config);
        $this->_logger = $logger ?? new NullLogger();
        $this->_initConnections();
    }

    protected function _initConnections()
    {
        $connections = [];
        if (isset($this->_config['connections'])) {
            foreach ($this->_config['connections'] as $connection) {
                if (is_array($connection)) {
                    $connections[] = Connection::create($connection);
                } else {
                    $connections[] = $connection;
                }
            }
        }

        if (empty($connections)) {
            $connections[] = Connection::create($this->_config);
        }
        if (isset($this->_config['connectionStrategy'])) {
            if (is_string($this->_config['connectionStrategy'])) {
                $strategyName = '\\Manticoresearch\\Connection\\Strategy\\' . $this->_config['connectionStrategy'];
                if (class_exists($strategyName)) {
                    $strategy = new $strategyName();
                } elseif (class_exists($this->_config['connectionStrategy'])) {
                    $strategyName = $this->_config['connectionStrategy'];
                    $strategy = new $strategyName();
                }
            } elseif ($this->_config['connectionStrategy'] instanceof SelectorInterface) {
                $strategy = $this->_config['connectionStrategy'];
            } else {
                throw new RuntimeException('Cannot create a strategy based on provided settings!');
            }
        } else {
            $strategy = new $this->_connectionStrategy;
        }
        if (!isset($this->_config['retries'])) {
            $this->_config['retries'] = count($connections);
        }
        $this->_connectionPool = new Connection\ConnectionPool($connections, $strategy ?? new $this->_connectionStrategy, $this->_config['retries']);
    }

    /**
     * @param string|array $hosts
     */
    public function setHosts($hosts)
    {
        $this->_config['connections'] = $hosts;
        $this->_initConnections();
    }

    /**
     * @param array $config
     * @return $this
     */
    public function setConfig(array $config): self
    {
        $this->_config = array_merge($this->_config, $config);
        return $this;
    }

    /**
     * @param array $config
     * @return Client
     */
    public static function create($config): Client
    {
        return self::createFromArray($config);
    }

    /**
     * @param array $config
     * @return Client
     */
    public static function createFromArray($config): Client
    {
        return new self($config);
    }

    /**
     * @return mixed
     */
    public function getConnections()
    {
        return $this->_connectionPool->getConnections();
    }

    /**
     * @return ConnectionPool
     */
    public function getConnectionPool(): ConnectionPool
    {
        return $this->_connectionPool;
    }

    /**
     * Endpoint: search
     * @param array $params
     * @param bool $obj
     * @return array|Response
     */
    public function search(array $params = [],$obj=false)
    {
        $endpoint = new Endpoints\Search($params);
        $response = $this->request($endpoint);
        if($obj ===true) {
            return $response;
        }else{
            return $response->getResponse();
        }
    }

    /**
     * Endpoint: insert
     * @param array $params
     * @return array
     */
    public function insert(array $params = [])
    {
        $endpoint = new Endpoints\Insert($params);
        $response = $this->request($endpoint);

        return $response->getResponse();
    }

    /**
     * Endpoint: replace
     * @param array $params
     * @return mixed
     */
    public function replace(array $params = [])
    {
        $endpoint = new Endpoints\Replace($params);
        $response = $this->request($endpoint);

        return $response->getResponse();
    }

    /**
     * Endpoint: update
     * @param array $params
     * @return array
     */
    public function update(array $params = [])
    {
        $endpoint = new Endpoints\Update($params);
        $response = $this->request($endpoint);

        return $response->getResponse();
    }

    /**
     * Endpoint: sql
     * @param array $params
     * @return array
     */
    public function sql(array $params = [])
    {
        $endpoint = new Endpoints\Sql($params);
        if (isset($params['mode'])) {
            $endpoint->setMode($params['mode']);
            $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
        } else {
            $response = $this->request($endpoint);
        }
        return $response->getResponse();
    }

    /**
     * Endpoint: delete
     * @param array $params
     * @return array
     */
    public function delete(array $params = [])
    {
        $endpoint = new Endpoints\Delete($params);
        $response = $this->request($endpoint);

        return $response->getResponse();
    }

    /**
     * Endpoint: pq
     */
    public function pq(): Pq
    {
        return new Pq($this);
    }

    /**
     * Endpoint: indices
     */
    public function indices(): Indices
    {
        return new Indices($this);
    }

    /**
     * Endpoint: nodes
     */
    public function nodes(): Nodes
    {
        return new Nodes($this);
    }

    public function cluster(): Cluster
    {
        return new Cluster($this);
    }

    /**
     * Endpoint: bulk
     * @param array $params
     * @return array
     */
    public function bulk(array $params = [])
    {
        $endpoint = new Endpoints\Bulk($params);
        $response = $this->request($endpoint);

        return $response->getResponse();
    }

    /**
     * Endpoint: suggest
     * @param array $params
     * @return array
     */
    public function suggest(array $params = [])
    {
        $endpoint = new Endpoints\Suggest();
        $endpoint->setIndex($params['index']);
        $endpoint->setBody($params['body']);
        $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
        return $response->getResponse();
    }

    public function keywords(array $params = [])
    {
        $endpoint = new Endpoints\Keywords();
        $endpoint->setIndex($params['index']);
        $endpoint->setBody($params['body']);
        $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
        return $response->getResponse();
    }


    /*
     * @return Response
     */

    public function request(Request $request, array $params = []): Response
    {
        try {
            $connection = $this->_connectionPool->getConnection();
            $this->_lastResponse = $connection->getTransportHandler($this->_logger)->execute($request, $params);
        } catch (NoMoreNodesException $e) {
            $this->_logger->error('Manticore Search Request out of retries:', [
                'exception' => $e->getMessage(),
                'request' => $request->toArray()
            ]);
            throw $e;
        } catch (ConnectionException $e) {
            $this->_logger->warning('Manticore Search Request failed ' . $this->_connectionPool->retries_attempts . ':', [
                'exception' => $e->getMessage(),
                'request' => $e->getRequest()->toArray()
            ]);

            if (isset($connection)) {
                $connection->mark(false);
            }

            return $this->request($request, $params);
        }
        return $this->_lastResponse;
    }
    /*
 *
 * @return Response
 */

    public function getLastResponse(): Response
    {
        return $this->_lastResponse;
    }

}