<?php

namespace KupShop\KupShopBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\CatalogBundle\Search\FulltextElastic;
use KupShop\CatalogBundle\Search\FulltextInterface;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class FulltextSearchDebug extends Script
{
    protected static $name = 'Debug fulltext vyhledávání';
    protected static $defaultParameters = [
        'text' => 'ahoj světe',
    ];

    protected function run(array $arguments)
    {
        $this->log('Vstupní parametry: ', print_r($arguments, true));
        $fulltext = ServiceContainer::getService(FulltextInterface::class);

        $url = $fulltext->getServerUrl().'/'.$fulltext->getIndex($fulltext::INDEX_PRODUCTS).'/_analyze';

        // Standardní fulltext hledání
        $result = $fulltext->curlInitSession($url, 'POST', json_encode([
            'text' => $arguments['text'],
            'analyzer' => 'icu_folding',
        ]));
        $this->log('Indexace standardní (analyzer=icu_folding)', print_r($result, true));

        $result = $fulltext->curlInitSession($url, 'POST', json_encode([
            'text' => $arguments['text'],
            'analyzer' => 'query',
        ]));
        $this->log('Vyhledávání standardní (analyzer=query)', print_r($result, true));

        // Hledání bez mezer
        $result = $fulltext->curlInitSession($url, 'POST', json_encode([
            'text' => $arguments['text'],
            'analyzer' => 'ngram_analyze',
        ]));
        $this->log('Indexace bez mezer (analyzer=ngram_analyze)', print_r($result, true));

        $result = $fulltext->curlInitSession($url, 'POST', json_encode([
            'text' => $arguments['text'],
            'analyzer' => 'ngram_search',
        ]));
        $this->log('Vyhledávání bez mezer (analyzer=ngram_search)', print_r($result, true));

        $params = json_decode($fulltext->productsSearchParameter($arguments['text'], 10, 0, 'weight', 'asc'), true);
        $params['explain'] = true;
        $url = $fulltext->getServerUrl().'/'.$fulltext->getIndex(FulltextElastic::INDEX_PRODUCTS).'/_doc/_search';
        $result = $fulltext->curlInitSession($url, 'GET', json_encode($params));
        $this->log('Vyhledávání produktů', print_r($result, true));
    }
}

return FulltextSearchDebug::class;
