<?php

declare(strict_types=1);

namespace KupShop\CatalogElasticBundle\Resources\script;

use Elastica\Query\AbstractQuery;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\CatalogBundle\ProductList\DynamicFilterAttributes;
use KupShop\CatalogBundle\Search\FulltextElastic;
use KupShop\CatalogBundle\View\CategoryRequestHandler;
use KupShop\CatalogElasticBundle\SectionRequest;
use KupShop\CatalogElasticBundle\Util\ElasticaFactory;
use KupShop\CatalogElasticBundle\Util\ElasticQueryClient;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class ExplainElasticSearchScript extends Script
{
    protected static $defaultParameters = [
        'productId' => 1234,
        'searchTerm' => 'Ahoj',
    ];

    protected static $name = '"Explain" na Elasticsearch query';

    private ElasticQueryClient $elasticQueryClient;
    private ElasticaFactory $elasticaFactory;
    private FulltextElastic $fulltextElastic;

    public function __construct()
    {
        $this->elasticQueryClient = ServiceContainer::getService(ElasticQueryClient::class);
        $this->elasticaFactory = ServiceContainer::getService(ElasticaFactory::class);
        $this->fulltextElastic = ServiceContainer::getService(FulltextElastic::class);
    }

    protected function run(array $arguments)
    {
        $productId = (int) $arguments['productId'];
        $term = $arguments['searchTerm'];

        $query = $this->getSearchQuery($term);

        echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.js" integrity="sha512-8RnEqURPUc5aqFEN04aQEiPlSAdE0jlFS/9iGgUyNtwFnSKCXhmB6ZTNl7LnDtDWKabJIASzXrzD0K+LYexU9g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>';
        echo '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css" integrity="sha512-uf06llspW44/LZpHzHT6qBOIVODjWtv4MxCricRxkzvopAlSWnTf6hpZTFxuuZcuNE9CBQhqE0Seu1CoRk84nQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />';
        echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/javascript/javascript.min.js" integrity="sha512-I6CdJdruzGtvDyvdO4YsiAq+pkWf2efgd1ZUSK2FnM/u2VuRASPC7GowWQrWyjxCZn6CT89s3ddGI+be0Ak9Fg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>';

        // folding
        echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/fold/foldgutter.min.js" integrity="sha512-kEVEkqJPlijyiRihpbPuhIW6wkb5wcEaVsfYm/utqn8ToMspk7E2fK5UyZ2HdnJnA4/0HyQwqeKzHNuPm+zyCw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>';
        echo '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/fold/foldgutter.min.css" integrity="sha512-YwkMTlTHn8dBnwa47IF+cKsS00HPiiVhQ4DpwT1KF2gUftfFR7aefepabSPLAs6zrMyD89M3w0Ow6mQ5XJEUCw==" crossorigin="anonymous" referrerpolicy="no-referrer" />';
        echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/fold/foldcode.min.js" integrity="sha512-Q2qfEJEU257Qlqc4/5g6iKuJNnn5L0xu2D48p8WHe9YC/kLj2UfkdGD01qfxWk+XIcHsZngcA8WuKcizF8MAHA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>';
        echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/addon/fold/brace-fold.min.js" integrity="sha512-5MuaB1PVXvhsYVG0Ozb0bwauN7/D1VU4P8dwo5E/xiB9SXY+VSEhIyxt1ggYk2xaB/RKqKL7rPXpm1o1IlTQDA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>';

        echo 'Query:<br>';
        echo '<textarea id="query">';
        echo json_encode($query->toArray(), JSON_PRETTY_PRINT).PHP_EOL;
        echo '</textarea>';

        $response = $this->elasticaFactory->getClient()->explain([
            'id' => $productId,
            'index' => $this->fulltextElastic->getIndex(FulltextElastic::INDEX_PRODUCTS),
            'body' => ['query' => $query->toArray()],
        ]);

        $response = json_decode((string) $response->getBody());

        echo '<hr>';
        echo 'Explain:<br>';
        echo '<textarea id="explain">';
        echo json_encode($response, JSON_PRETTY_PRINT).PHP_EOL;
        echo '</textarea>';

        echo '<script type="text/javascript">';
        // language=JS
        echo <<<__JS__
            CodeMirror.fromTextArea(document.getElementById('query'), {
                lineNumbers: true,
                mode: "application/json",
                matchBrackets: true,
                autoCloseBrackets: true,
                foldGutter: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
            });
            
            CodeMirror.fromTextArea(document.getElementById('explain'), {
                lineNumbers: true,
                mode: "application/json",
                matchBrackets: true,
                autoCloseBrackets: true,
                foldGutter: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
            });
        __JS__;
        echo '</script>';
    }

    private function getSearchQuery(string $searchTerm): AbstractQuery
    {
        $filterParams = new \FilterParams();
        $filterParams->setSearch($searchTerm);

        $baseFilterParams = new \FilterParams();
        $baseFilterParams->setSectionsFilter([CategoryRequestHandler::SEARCH_CATEGORY_ID]);

        $request = new SectionRequest(
            filterParams: $filterParams,
            baseFilterParams: $baseFilterParams,
        );

        $preparedQuery = $this->elasticQueryClient->prepareSectionQuery(
            $request,
            new \ProductList(),
            new \Filter(),
            new \Pager(),
            DynamicFilterAttributes::empty(),
        );

        $ms = $preparedQuery->createMultiSearch();

        return $ms->getSearches()[ElasticQueryClient::$mainQueryName]
            ->getQuery()
            ->getQuery();
    }
}

return ExplainElasticSearchScript::class;
