<?php

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\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;
use Symfony\Component\Form\Extension\Core\Type\FileType as BaseFileType;

/**
 * @author Colinet Julien
 */
class FileType extends AbstractType
{
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['title'] = $options['title'];
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $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)
    {
        /** @var File $file */
        $file = $event->getData();
        $form = $event->getForm();
        if ($event->getData() && !empty($event->getData())) {
            if ($file->getPath()) {
                $form->remove('file');
                $form->add(
                    'file', BaseFileType::class, [
                        'label'    => 'false',
                        'required' => false,
                    ]
                );
            }
        }
    }

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

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