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

use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class PickLinkedAccompanyingPeriodWorkType extends AbstractType
{
    public function __construct(private readonly NormalizerInterface $normalizer) {}

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['multiple'] = $options['multiple'];
        $view->vars['types'] = ['acpw'];
        $view->vars['uniqid'] = uniqid('pick_acpw_dyn');
        $view->vars['suggested'] = [];
        $view->vars['as_id'] = true === $options['as_id'] ? '1' : '0';
        $view->vars['submit_on_adding_new_entity'] = false;
        $view->vars['pick-entities-type'] = 'acpw';
        $view->vars['attr']['data-accompanying-period-id'] = $options['accompanyingPeriod']->getId();

        foreach ($options['suggested'] as $suggestion) {
            $view->vars['suggested'][] = $this->normalizer->normalize($suggestion, 'json', ['groups' => 'read']);
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setRequired('accompanyingPeriod')
            ->setAllowedTypes('accompanyingPeriod', [AccompanyingPeriod::class])
            ->setDefault('multiple', false)
            ->setAllowedTypes('multiple', ['bool'])
            ->setDefault('compound', false)
            ->setDefault('suggested', [])
            ->setDefault('as_id', false)
            ->setAllowedTypes('as_id', ['bool'])
            ->setDefault('submit_on_adding_new_entity', false)
            ->setAllowedTypes('submit_on_adding_new_entity', ['bool']);
    }

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