<?php

namespace App\Form;

use App\Entity\AreaFormacao;
use App\Entity\Bairro;
use App\Entity\Usuario;
use App\Repository\AreaFormacaoRepository;
use App\Repository\BairroRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RoleUserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('roles',ChoiceType::class,[
                'choices'=> array(
                    'TÉCNICO' => 'ROLE_USER',
                    'ADMINISTRADOR' => 'ROLE_ADMIN',
                    'MÉDICO' => 'ROLE_MEDICO_ADMIN',
                    'SECRETÁRIO' => 'ROLE_SECRE_ADMIN'
                )
            ])
            ->add('formacao',EntityType::class,[
                'class'=> AreaFormacao::class,
                'choice_label' => 'nome',
                'label' => 'Empresa',
                'query_builder' => function(AreaFormacaoRepository $areaFormacaoRepository){
                    return $areaFormacaoRepository->createQueryBuilder('e')
                        ->orderBy('e.nome','ASC');
                }
            ])
            ->add('bairro',EntityType::class,[
                'class'=> Bairro::class,
                'choice_label' => 'nome',
                'label' => 'Bairro',
                'query_builder' => function(BairroRepository $bairroRepository){
                    return $bairroRepository->createQueryBuilder('e')
                        ->orderBy('e.nome','ASC');
                }
            ])
            ->add('telefone')
            ->add('isAtivo')

        ;
        $builder->get('roles')
            ->addModelTransformer(new CallbackTransformer(
                function ($rolesArray) {
                    // transform the array to a string
                    return count($rolesArray)? $rolesArray[0]: null;
                },
                function ($rolesString) {
                    // transform the string back to an array
                    return [$rolesString];
                }
            ));
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Usuario::class,
        ]);
    }
}
