<?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;

use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\Identifier\IdentifierPresenceEnum;
use Chill\PersonBundle\Form\DataMapper\PersonIdentifiersDataMapper;
use Chill\PersonBundle\PersonIdentifier\PersonIdentifierManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class PersonIdentifiersType extends AbstractType
{
    public function __construct(
        private readonly PersonIdentifierManagerInterface $identifierManager,
        private readonly PersonIdentifiersDataMapper $identifiersDataMapper,
        private readonly TranslatableStringHelperInterface $translatableStringHelper,
    ) {}

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        foreach ($this->identifierManager->getWorkers() as $k => $worker) {
            if (!$worker->getDefinition()->isEditableByUsers()) {
                continue;
            }

            // skip some on creation
            if ('on_create' === $options['step']
                && IdentifierPresenceEnum::ON_EDIT === $worker->getDefinition()->getPresence()) {
                continue;
            }

            $subBuilder = $builder->create(
                'identifier_'.$worker->getDefinition()->getId(),
                options: [
                    'compound' => true,
                    'label' => $this->translatableStringHelper->localize($worker->getDefinition()->getLabel()),
                    'error_bubbling' => false,
                ]
            );
            $subBuilder->setDataMapper($this->identifiersDataMapper);
            $worker->buildForm($subBuilder);
            $builder->add($subBuilder);
        }
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefault('step', 'on_edit')
            ->setAllowedValues('step', ['on_edit', 'on_create']);
    }
}
