<?php

namespace AutoAdmin\Bundle\Admin\Form\Type\Component;

use AutoAdmin\Bundle\Admin\EventListener\Form\CollectionOrderListener;
use AutoAdmin\Bundle\Content\Model\SequencedInterface;
use ReflectionClass;
use Symfony\Component\Form\Extension\Core\Type\CollectionType as BaseCollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CollectionType extends BaseCollectionType
{
    protected array $keysOrder = [];

    protected array $defaultEntryOptions = ['label' => false,];

    public function configureOptions(OptionsResolver $resolver): void
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults(
            [
                'entry_type' => null,
                'by_reference' => false,
                'entry_options' => $this->defaultEntryOptions,
                'allow_add' => true,
                'allow_delete' => true,
                'allow_sort' => null,// default null
                'delete_empty' => true,
            ]
        );
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $options['entry_options'] = array_merge($this->defaultEntryOptions, $options['entry_options'] ?? []);

        parent::buildForm($builder, $options);

        $builder->addEventSubscriber(new CollectionOrderListener());
    }

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

        // here, if null, option is kept as default so we are trying to "guess" what is wanted
        if ($options['allow_sort'] === null) {
            $allowSort = true;
            $entryOptClass = $options['entry_options']['class'] ?? null;
            if ($entryOptClass !== null && class_exists($entryOptClass)) {
                $refl = new ReflectionClass($entryOptClass);
                if (!$refl->implementsInterface(SequencedInterface::class)) {
                    $allowSort = false;
                }
            }

            $options['allow_sort'] = $allowSort;
        }

        $view->vars = array_replace($view->vars, ['allow_sort' => $options['allow_sort'],]);
    }

    public function getBlockPrefix(): string
    {
        return 'aa_admin_collection';
    }
}
