<?php

namespace KupShop\ComponentsBundle\Twig\Components\EditableContent;

use KupShop\CatalogBundle\Repository\ProducersRepository;
use KupShop\ComponentsBundle\Attributes\Blocek;
use KupShop\ComponentsBundle\Attributes\BlocekAttribute;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Entity\Thumbnail;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ComponentsBundle\Twig\Components\Utils\EditableContent\BlocekDataTrait;
use KupShop\KupShopBundle\Util\System\UrlFinder;
use Query\Operator;
use Query\QueryBuilder;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\TwigComponent\Attribute\PostMount;

#[AsLiveComponent(template: '@Components/components/EditableContent/Producers/Producers.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
#[Blocek(title: 'Loga výrobců', descr: 'Pás s logy výrobců.', icon: 'producer-list.svg')]
class Producers extends BaseComponent
{
    use BlocekDataTrait;
    use DefaultActionTrait;

    #[LiveProp]
    #[BlocekAttribute(title: 'Počet log')]
    public int $limit = 5;
    #[LiveProp]
    #[BlocekAttribute(title: 'Přeskočit prvních')]
    public int $offset = 0;
    #[LiveProp]
    #[BlocekAttribute(title: 'Režim tmavého pozadí')]
    public bool $darkMode = false;

    #[LiveProp]
    #[BlocekAttribute(title: 'Odkaz na všechny značky')]
    public bool $showMoreLink = false;

    public function __construct(private readonly ProducersRepository $producersRepository, private readonly UrlFinder $urlFinder)
    {
    }

    #[PostMount]
    public function prepareSpecs(): void
    {
        $this->clearSpecs();

        if ($this->limit > 0) {
            $this->addSpec(function (QueryBuilder $qb) {
                $qb->setMaxResults($this->limit);
            });
        }

        if ($this->offset > 0) {
            $this->addSpec(function (QueryBuilder $qb) {
                $qb->setFirstResult($this->offset);
            });
        }

        $this->addSpec(function (QueryBuilder $qb) {
            $qb->andWhere(Operator::equals(['pr.top' => 'Y']));
        });
    }

    public function producers(): iterable
    {
        $this->producersRepository->setSecs($this->getSpecs());
        foreach ($this->producersRepository->getProducers() as $value) {
            if ($value['image'] ?? false) {
                $value['thumbnail'] = new Thumbnail((string) $value['image']['id'], $value['image']['descr'], (string) $value['image']['date_update']);
            }
            $value['url'] = createScriptURL([
                's' => 'category',
                'IDcat' => '0',
                'IDpd' => $value['id'],
                'producerTitle' => $value['name'],
            ]);
            yield $value;
        }
    }
}
