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

use Chill\ActivityBundle\Entity\ActivityReason;
use Chill\ActivityBundle\Repository\ActivityReasonRepository;
use Chill\ActivityBundle\Templating\Entity\ActivityReasonRender;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * FormType to choose amongst activity reasons.
 */
class PickActivityReasonType extends AbstractType
{
    public function __construct(
        private readonly ActivityReasonRepository $activityReasonRepository,
        private readonly ActivityReasonRender $reasonRender,
        private readonly TranslatableStringHelperInterface $translatableStringHelper,
    ) {}

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'class' => ActivityReason::class,
                'choice_label' => fn (ActivityReason $choice) => $this->reasonRender->renderString($choice, []),
                'group_by' => function (ActivityReason $choice): ?string {
                    if (null !== $category = $choice->getCategory()) {
                        return $this->translatableStringHelper->localize($category->getName());
                    }

                    return null;
                },
                'choices' => $this->activityReasonRepository->findAll(),
                'attr' => ['class' => ' select2 '],
            ]
        );
    }

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

    public function getParent()
    {
        return EntityType::class;
    }
}
