<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin;

use CpCreation\VitiCore\User\Model\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;

class UserType extends AbstractType
{

    private $roles = [];

    public function __construct(RoleHierarchyInterface $roleHierarchy)
    {
        $roleHierarchy = (array)$roleHierarchy;
        $roleHierarchy = array_shift($roleHierarchy);
        foreach ($roleHierarchy as $key => $role) {
            $this->roles[$key] = $key;
        }
        asort($this->roles);
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'username', TextType::class, [
                    'label'    => 'Identifiant',
                    'required' => true,
                ]
            )
            ->add(
                'email', EmailType::class, [
                    'label'    => 'Email',
                    'required' => true,
                ]
            )
            ->add(
                'roles', ChoiceType::class, [
                    'label'        => 'Roles',
                    'multiple'     => true,
                    'choices'      => $this->roles,
                    'choice_label' => function ($choice) {
                        return strtoupper($choice);
                    },
                    'attr'         => [
                        'class' => 'select2',
                    ],
                    'required'     => true,
                ]
            )
            ->addEventListener(
                FormEvents::PRE_SET_DATA,
                [$this, 'onPreSetData']
            );

    }

    public function onPreSetData(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();

        if ($data) {
            $form->add(
                'plainPassword', PasswordType::class, [
                    'label'    => 'Mot de passe',
                    'required' => false,
                ]
            );
        } else {
            $form->add(
                'plainPassword', PasswordType::class, [
                    'label'    => 'Mot de passe',
                    'required' => true,
                ]
            );
        }
    }

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