<?php

namespace AutoAdmin\Bundle\Media\Form\Type;

use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;


/**
 * Inspired by :https://github.com/dustin10/VichUploaderBundle/blob/master/src/Form/Type/VichImageType.php
 */
class ImageType extends FileType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults(
            [
                'data_class' => $this->config['classes']['image'],
                'mime_types' => $this->config['mime_types']['image'],
                'mapping' => 'default',
                'alt_options' => [
                    'required' => false,
                    'label' => 'media.image.alt',
                    'translation_domain' => 'aa_admin',
                ],
            ],
        );
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        parent::buildForm($builder, $options);

        $builder->add('alt', TextType::class, $options['alt_options']);
        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) {
                $data = $event->getData();
                if ($data) {
                    $event->getForm()->add('id', HiddenType::class);
                }
            }
        );
    }

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