<?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\Form\DataMapper\RollingDateDataMapper;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class PickRollingDateType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('roll', ChoiceType::class, [
                'choices' => array_combine(
                    array_map(static fn (string $item) => 'rolling_date.'.$item, RollingDate::ALL_T),
                    RollingDate::ALL_T
                ),
                'multiple' => false,
                'expanded' => false,
                'required' => $options['required'],
                'label' => 'rolling_date.roll_movement',
            ])
            ->add('fixedDate', ChillDateType::class, [
                'input' => 'datetime_immutable',
                'label' => 'rolling_date.fixed_date_date',
            ]);

        $builder->setDataMapper(new RollingDateDataMapper());
    }

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

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'class' => RollingDate::class,
            'empty_data' => null,
            'constraints' => [
                new Callback($this->validate(...)),
            ],
            'required' => true,
        ]);

        $resolver->setAllowedTypes('required', 'bool');
    }

    public function validate($data, ExecutionContextInterface $context, $payload): void
    {
        if (null === $data) {
            return;
        }

        /** @var RollingDate $data */
        if (RollingDate::T_FIXED_DATE === $data->getRoll() && null === $data->getFixedDate()) {
            $context
                ->buildViolation('rolling_date.When fixed date is selected, you must provide a date')
                ->atPath('fixedDate')
                ->addViolation();
        }
    }
}
