<?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\MainBundle\Templating\Entity\ChillEntityRenderExtension;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Entity\AccompanyingPeriod\ClosingMotive;
use Chill\PersonBundle\Repository\AccompanyingPeriod\ClosingMotiveRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class ClosingMotivePickerType
 * A type to add a closing motive.
 */
class ClosingMotivePickerType extends AbstractType
{
    /**
     * @var ChillEntityRenderExtension
     */
    protected $entityRenderExtension;

    /**
     * @var ClosingMotiveRepository
     */
    protected $repository;

    /**
     * @var TranslatableStringHelper
     */
    protected $translatableStringHelper;

    /**
     * ClosingMotivePickerType constructor.
     */
    public function __construct(
        TranslatableStringHelper $translatableStringHelper,
        ChillEntityRenderExtension $chillEntityRenderExtension,
        ClosingMotiveRepository $closingMotiveRepository,
    ) {
        $this->translatableStringHelper = $translatableStringHelper;
        $this->entityRenderExtension = $chillEntityRenderExtension;
        $this->repository = $closingMotiveRepository;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'class' => ClosingMotive::class,
            'empty_data' => null,
            'placeholder' => 'Choose a motive',
            'choice_label' => fn (ClosingMotive $cm) => $this->entityRenderExtension->renderString($cm),
            'only_leaf' => true,
        ]);

        $resolver
            ->setAllowedTypes('only_leaf', 'bool')
            ->setNormalizer('choices', fn (Options $options) => $this->repository
                ->getActiveClosingMotive($options['only_leaf']));
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'closing_motive';
    }

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