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

use Chill\CustomFieldsBundle\Form\Type\CustomFieldType;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Form\Type\AppendScopeChoiceTypeTrait;
use Chill\MainBundle\Form\Type\ChillDateType;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

final class ReportType extends AbstractType
{
    use AppendScopeChoiceTypeTrait;

    public function __construct(
        private readonly AuthorizationHelper $authorizationHelper,
        private readonly TokenStorageInterface $tokenStorage,
        private readonly TranslatableStringHelper $translatableStringHelper,
        private readonly ObjectManager $om,
    ) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('user')
            ->add(
                'date',
                ChillDateType::class,
                ['required' => true]
            )
            ->add(
                'cFData',
                CustomFieldType::class,
                ['attr' => ['class' => 'cf-fields'],
                    'group' => $options['cFGroup'], ]
            );

        $user = $this->tokenStorage->getToken()->getUser();

        if (!$user instanceof User) {
            throw new \RuntimeException('user must be a regular user');
        }

        $this->appendScopeChoices(
            $builder,
            $options['role'],
            $options['center'],
            $user,
            $this->authorizationHelper,
            $this->translatableStringHelper,
            $this->om
        );
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => \Chill\ReportBundle\Entity\Report::class,
        ]);

        $resolver->setRequired([
            'cFGroup',
        ]);

        $resolver->setAllowedTypes('cFGroup', \Chill\CustomFieldsBundle\Entity\CustomFieldsGroup::class);

        $this->appendScopeChoicesOptions($resolver);
    }

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