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

use Chill\MainBundle\Form\Utils\PermissionsGroupFlagProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PermissionsGroupType extends AbstractType
{
    final public const FLAG_SCOPE = 'permissions_group';

    /**
     * @var PermissionsGroupFlagProvider[]
     */
    protected $flagProviders = [];

    public function addFlagProvider(PermissionsGroupFlagProvider $provider)
    {
        $this->flagProviders[] = $provider;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class);

        $flags = $this->getFlags();

        if (\count($flags) > 0) {
            $builder
                ->add('flags', ChoiceType::class, [
                    'choices' => \array_combine($flags, $flags),
                    'multiple' => true,
                    'expanded' => true,
                    'required' => false,
                ]);
        }
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => \Chill\MainBundle\Entity\PermissionsGroup::class,
        ]);
    }

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

    protected function getFlags(): array
    {
        $flags = [];

        foreach ($this->flagProviders as $flagProvider) {
            $flags = \array_merge($flags, $flagProvider->getPermissionsGroupFlags());
        }

        return $flags;
    }
}
