<?php

namespace App\User\Framework\Form;

use Aimeos\Map;
use App\User\Database\CountryLanguages;
use App\User\Database\ProviderList;
use App\User\Database\QualityList;
use App\User\Framework\Repository\PreferenceOptionRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class GettingStartedFilterForm extends AbstractType
{
    public function __construct(
        private readonly PreferenceOptionRepository $preferenceOptionRepository,
    ) {}

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $this->addChoiceField($builder, 'language', CountryLanguages::asSelectOptions());
        $this->addChoiceField($builder, 'quality', QualityList::asSelectOptions());
        $this->addChoiceField($builder, 'provider', ProviderList::asSelectOptions());
        $this->addChoiceField($builder, 'resolution', $this->getPreferenceChoices('resolution'));
        $this->addChoiceField($builder, 'codec', $this->getPreferenceChoices('codec'));
    }

    private function addChoiceField(FormBuilderInterface $builder, string $fieldName, array $choices): void
    {
        $question = [
            'attr' => ['class' => 'w-full text-input mb-4'],
            'label_attr' => ['class' => 'w-full block font-semibold'],
            'choices' => $this->addDefaultChoice($choices),
        ];
        $builder->add($fieldName, ChoiceType::class, $question);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([]);
    }

    private function getPreferenceChoices(string $preference): array
    {
        $options = $this->preferenceOptionRepository->findBy(['preference' => $preference]);
        $result = [];
        foreach ($options as $item) {
            $result[$item->getName()] = $item->getId();
        }
        return $result;
    }

    private function addDefaultChoice(array $choices): iterable
    {
        return ['n/a' => null] + $choices;
    }
}
