<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\CustomFieldsBundle\Form\Type;

use Chill\MainBundle\Form\Type\TranslatableStringFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class ChoicesListType extends AbstractType
{
    /** (non-PHPdoc).
     * @see \Symfony\Component\Form\AbstractType::buildForm()
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', TranslatableStringFormType::class)
            ->add('active', CheckboxType::class, [
                'required' => false,
            ])
            ->add('slug', HiddenType::class)
            ->addEventListener(FormEvents::SUBMIT, static function (FormEvent $event) {
                $form = $event->getForm();
                $data = $event->getData();

                $formData = $form->getData();

                if (null === $formData['slug']) {
                    $slug = uniqid(random_int(0, mt_getrandmax()), true);

                    $data['slug'] = $slug;
                    $event->setData($data);
                } else {
                    $data['slug'] = $formData['slug'];
                    $event->setData($data);
                }
            });
    }

    /**
     * @see \Symfony\Component\Form\FormTypeInterface::getName()
     */
    public function getBlockPrefix()
    {
        return 'cf_choices_list';
    }
}
