<?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\MainBundle\Form\Type;

use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable;
use Symfony\Component\Form\AbstractType;
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\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class CommentType extends AbstractType
{
    /**
     * @var \Symfony\Component\Security\Core\User\UserInterface
     */
    protected $user;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->user = $tokenStorage->getToken()->getUser();
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('comment', ChillTextareaType::class, [
                'disable_editor' => $options['disable_editor'],
                'label' => $options['label'],
            ]);

        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
            $data = $event->getForm()->getData();
            $comment = $event->getData() ?? ['comment' => ''];

            if (null !== $data && $data->getComment() !== $comment['comment']) {
                $data->setDate(new \DateTime());
                $data->setUserId($this->user->getId());
                $event->getForm()->setData($data);
            }
        });
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['fullWidth'] = true;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefined('disable_editor')
            ->setAllowedTypes('disable_editor', 'bool')
            ->setDefaults([
                'data_class' => CommentEmbeddable::class,
                'disable_editor' => false,
            ]);
    }
}
