<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Form\Filter;

use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Contracts\Translation\TranslatableInterface;

abstract class AbstractFilterType extends AbstractType
{
    private ?string $section = null;
    private int $priority = 0;
    private array $views = [];

    abstract public function apply(QueryBuilder $qb, FormInterface $form): void;

    public function supports(string $viewId): bool
    {
        if (empty($this->views)) {
            return true;
        }

        return \in_array($viewId, $this->views, true);
    }

    public function getSection(): string
    {
        return $this->section ?? 'default';
    }

    public function getPriority(): int
    {
        return $this->priority;
    }

    public function setSection(?string $section): void
    {
        $this->section = $section;
    }

    public function setPriority(int $priority): void
    {
        $this->priority = $priority;
    }

    public function setViews(array $views): void
    {
        $this->views = $views;
    }

    /**
     * Allows you to modify whether the filter shall be displayed in the form, regardless of whether the filter is applied.
     */
    public function shallDisplay(?string $viewId = null): bool
    {
        return true;
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        parent::buildView($view, $form, $options);

        $viewId = $form->getParent()?->getConfig()->getOption('view_id');

        $view->vars['isEmpty'] = $form->isEmpty();
        $view->vars['humanReadable'] = $this->getHumanReadableValue($form);
        $view->vars['display'] = $this->shallDisplay($viewId);
        $view->vars['section'] = $this->getSection();
    }

    abstract protected function getHumanReadableValue(FormInterface $form): string|TranslatableInterface|null;
}
