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

use Chill\MainBundle\Form\Type\ChillDateType;
use Chill\MainBundle\Form\Type\ChillTextareaType;
use Chill\MainBundle\Form\Type\DateIntervalType;
use Chill\MainBundle\Form\Type\ScopePickerType;
use Chill\MainBundle\Form\Type\UserPickerType;
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcherInterface;
use Chill\MainBundle\Security\Resolver\ScopeResolverDispatcher;
use Chill\TaskBundle\Security\Authorization\TaskVoter;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SingleTaskType extends AbstractType
{
    public function __construct(
        private readonly ParameterBagInterface $parameterBag,
        private readonly CenterResolverDispatcherInterface $centerResolverDispatcher,
        private readonly ScopeResolverDispatcher $scopeResolverDispatcher,
    ) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $center = null;
        $isScopeConcerned = false;

        if (null !== $task = $options['data']) {
            $center = $this->centerResolverDispatcher->resolveCenter($task);
            $isScopeConcerned = $this->scopeResolverDispatcher->isConcerned($task);
        }

        $builder
            ->add('title', TextType::class)
            ->add('description', ChillTextareaType::class, [
                'required' => false,
            ])
            ->add('assignee', UserPickerType::class, [
                'required' => false,
                'center' => $center,
                'role' => TaskVoter::SHOW,
                'placeholder' => 'Not assigned',
                'attr' => ['class' => ' select2 '],
            ])
            ->add('startDate', ChillDateType::class, [
                'required' => false,
            ])
            ->add('endDate', ChillDateType::class, [
                'required' => false,
            ])
            ->add('warningInterval', DateIntervalType::class, [
                'required' => false,
            ]);

        if ($isScopeConcerned && $this->parameterBag->get('chill_main')['acl']['form_show_scopes']) {
            $builder
                ->add('circle', ScopePickerType::class, [
                    'role' => $options['role'],
                    'subject' => $task,
                    'required' => true,
                ]);
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setRequired('role')
            ->setAllowedTypes('role', ['string']);
    }
}
