<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin;

use CpCreation\VitiCore\Media\Model\File;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType as BaseFileType;
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\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class FileType extends AbstractType
{
    public function buildView(FormView $view, FormInterface $form, array $options): void
    {
        $view->vars['title'] = $options['title'];
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add(
                'file', BaseFileType::class, [
                    'label' => false,
                    'multiple' => false,
                ]
            )
            ->add(
                'title', TextType::class, [
                    'label' => 'Titre du document',
                    'attr' => [
                        'class' => 'file-title',
                    ],
                    'required' => false,
                ]
            )->addEventListener(
                FormEvents::PRE_SET_DATA,
                [$this, 'onPreSetData']
            );
    }

    public function onPreSetData(FormEvent $event): void
    {
        $data = $event->getData();

        if (!$data instanceof File) {
            return;
        }

        if (!$data->getPath()) {
            return;
        }

        $form = $event->getForm();

        if ($form->has('file')) {
            $form->remove('file');
        }

        $form->add('file', BaseFileType::class, [
            'label' => false,
            'required' => false,
        ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(
            [
                'data_class' => File::class,
                'title' => false,
                'required' => false,
            ]
        );
    }

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