<?php

namespace AutoAdmin\Bundle\Admin\Form;

use AutoAdmin\Bundle\Admin\Form\Transformer\HiddenEntityTransformer;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class HiddenEntityType extends AbstractType
{
    private EntityManagerInterface $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setRequired(
            [
                'class',
            ]
        );
        $resolver->setDefaults(
            [
                'class' => null,
                // primary key
                'pk' => null,
            ]
        );
        parent::configureOptions($resolver);
    }

    /**
     * @inheritDoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        // attach the specified model transformer for this entity list field
        // this will convert data between object and string formats
        $transformer = new HiddenEntityTransformer($this->em, $options['class'], $options['pk']);

        $builder->addModelTransformer($transformer);

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

    /**
     * @inheritDoc
     */
    public function getParent(): ?string
    {
        return HiddenType::class;
    }
}
