<?php

namespace KupShop\CatalogElasticBundle\Resources\upgrade;

use KupShop\CatalogBundle\Search\FulltextElastic;
use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class FullTextUpgrade extends \UpgradeNew
{
    protected $priority = 3000;

    public function check_FullTextIsGenerated()
    {
        $fulltext = ServiceContainer::getService(FulltextElastic::class);

        try {
            $result = $fulltext->getAllIndices();
        } catch (\Exception $e) {
            return false;
        }

        return empty($result);
    }

    /** FullText - generate indexes when they are not generated */
    public function upgrade_FullTextIsGenerated()
    {
        $fulltext = ServiceContainer::getService(FulltextElastic::class);
        $contextManager = ServiceContainer::getService(ContextManager::class);

        foreach ($fulltext->getFulltextLanguages() as $language => $_) {
            $contextManager->activateContexts([LanguageContext::class => $language], function () use ($fulltext) {
                $fulltext->updateIndex();
            });
        }

        $this->upgradeOK();
    }
}
