<?php

use KupShop\AdminBundle\Query\Invert;
use KupShop\FeedsBundle\Exceptions\UnknownFeedTypeException;
use KupShop\FeedsBundle\FeedLocator;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\HtmlBuilder\HTML;
use Query\Operator;

class FeedsList extends \KupShop\AdminBundle\AdminList\BaseList
{
    protected $tableName = 'feeds';

    protected ?string $tableAlias = 'f';

    protected $tableDef = [
        'id' => 'id',
        'fields' => [
            'Název' => ['field' => 'name'],
            'Typ' => ['field' => 'type', 'render' => 'renderType'],
            'Poznámka' => ['field' => 'note', 'spec' => "JSON_VALUE(data, '$.note') AS note"],
            'Jazyk' => ['field' => 'id_language', 'size' => 0.4],
            'Měna' => ['field' => 'id_currency', 'size' => 0.4],
            'Aktivní' => ['field' => 'active', 'render' => 'renderBoolean', 'size' => 0.4],
            'Předgenerovávat' => ['field' => 'expensive', 'render' => 'renderBoolean', 'size' => 0.4, 'visible' => 'N'],
            'Vygenerováno' => ['field' => 'regenerated', 'size' => 0.7],
            'Staženo' => ['field' => 'last_download', 'size' => 0.7],
            'Chyby' => ['field' => '', 'render' => 'renderErrors', 'size' => 0.5],
            'Počty' => ['field' => '', 'render' => 'renderCount', 'size' => 0.5],
            'Ukázka' => ['field' => 'id', 'render' => 'renderPreview', 'class' => 'alignRight text-right', 'size' => 0.4],
        ],
    ];

    /** @var FeedLocator */
    private $feedLocator;

    public function __construct()
    {
        $this->feedLocator = ServiceContainer::getService(FeedLocator::class);
    }

    public function getFilterQuery(): Query\QueryBuilder
    {
        $qb = parent::getFilterQuery();

        $filterFeedMapID = getVal('filterFeedMapID');
        if (!empty($filterFeedMapID)) {
            $feedMapName = sqlQueryBuilder()->select('name')->from('feed_maps')
                ->where(\Query\Operator::equals(['id' => $filterFeedMapID]))
                ->setMaxResults(1)->execute()->fetchColumn(0);
            if (!empty($feedMapName)) {
                $qb->andWhere(\Query\Operator::orX(
                    'INSTR(template, :mapName1)',
                    'INSTR(template, :mapName2)'
                ))
                    ->setParameter('mapName1', '("'.$feedMapName.'"')
                    ->setParameter('mapName2', "('".$feedMapName."'");
            }
        }

        if ($id = getVal('id')) {
            $qb->andWhere(Operator::equals(['id' => $id]));
        }

        if ($names = getVal('title')) {
            $search_fields = [
                ['field' => 'f.name', 'match' => 'both'],
            ];
            $qb->andWhere(\KupShop\CatalogBundle\Query\Search::searchFields($names, $search_fields));
        }

        if ($type = getVal('feedType')) {
            $qb->andWhere(Invert::checkInvert(Operator::inStringArray($type, 'f.type'), getVal('type_invert')));
        }

        if ($active = getVal('active')) {
            $qb->andWhere(Invert::checkInvert(Operator::inIntArray($active, 'f.active'), getVal('active_invert')));
        }

        $searchNote = getVal('searchNote');
        if (!empty($searchNote)) {
            $qb->andWhere(Operator::like(["JSON_VALUE(data, '$.note')" => '%'.$searchNote.'%']));
        }

        $searchTemplate = getVal('searchTemplate');
        if (!empty($searchTemplate)) {
            $tmpSearchTemplate = addcslashes($searchTemplate, '%_\\');
            $tmpSearchTemplate = str_replace('\\', '\\\\', $tmpSearchTemplate);
            $qb->andWhere(Operator::like(['template' => '%'.$tmpSearchTemplate.'%']));
        }

        return $qb;
    }

    public function renderType($feed, $fieldSettings)
    {
        try {
            return $this->feedLocator->getAliasByType($feed['type']);
        } catch (UnknownFeedTypeException $exception) {
            return 'Neznámý typ feedu: '.$exception->getMessage();
        }
    }

    public function renderErrors($feed, $fieldSettings)
    {
        $report = json_decode($feed['report'] ?? '');
        if (isset($report->count) && isset($report->validCount)) {
            $errorsCount = ($report->count ?? 0) - ($report->validCount ?? 0);
            if ($errorsCount <= 0) {
                return $this->renderIcon('success', 'Ano', 'Nebyly zachyceny žádné chyby');
            } else {
                return HTML::create('strong')
                    ->attr('title', 'Počet chyb')
                    ->text($errorsCount);
            }
        } else {
            return '';
        }
    }

    public function renderCount($feed, $fieldSettings)
    {
        $report = json_decode($feed['report'] ?? '');
        if (isset($report->validInStoreCount) && isset($report->validCount)) {
            return HTML::create('span')
                ->attr('title', 'Skladem | Není skladem')
                ->text($report->validInStoreCount.' | '.($report->validCount - $report->validInStoreCount));
        } else {
            return '';
        }
    }

    public function renderPreview($feed, $fieldSettings)
    {
        return HTML::create('a')
            ->attr('href', path('kupshop_feeds_feed_export', ['feedID' => $feed['id'], 'hash' => $feed['hash'], 'limit' => 50]))
            ->attr('target', '_blank')
            ->class('btn btn-xs btn-secondary')
            ->tag('span')
                ->class('bi bi-search')
                ->end()
            ->attr('title', translate('feed_preview_short', 'feeds'));
    }
}
