<?php

/**
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace LifeStyle\Tools\BackendSecurityBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use LifeStyle\Tools\BackendSecurityBundle\Entity\User as UserEntity;

/**
 * Class User
 * @package LifeStyle\Tools\BackendSecurityBundle\Form
 */
class User extends AbstractType
{
    /**
     * @var array
     */
    private $roleHierarchy;

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->roleHierarchy = $options['roles'] ? $options['roles'] : [];

        $builder
            ->add('Username')
            ->add('Email')
            ->add('Firstname')
            ->add('Lastname')
            ->add('Organisation')
            ->add('PlainPassword', PasswordType::class, array('label' => 'Password', 'required' => false))
            ->add('Enabled', ChoiceType::class, array(
                'choices' => array(
                    0 => 'No',
                    1 => 'Yes',
                )
            ))
            ->add('Roles', ChoiceType::class, array(
                'choices' => $this->getExistingRoles(),
                'multiple' => true,
                'expanded' => true,
                'label' => 'Roles (ROLE_USER is added automatically)'
            ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'lifestyle_backendsecuritybundle_user';
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => UserEntity::class,
            'roles' => null
        ));
    }

    /**
     * @return array
     */
    private function getExistingRoles()
    {
        $roles = array_keys($this->roleHierarchy);
        return array_combine($roles, $roles);
    }
}
