<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private 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
 * @link       http://www.life-style.de
 */

namespace Sso\BackendBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Class WsApplicationUsers
 * @package Sso\BackendBundle\Form
 */
class WsApplicationUsers extends AbstractType
{
    /**
     * @var RequestStack
     */
    private $requestStack;

    /**
     * WsApplicationUsers constructor.
     * @param RequestStack $requestStack
     */
    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->setAttribute('role', 'form')
            ->add('submit', 'submit', ['label' => 'Save']);

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) {
                $form = $event->getForm();
                $form->add(
                    'Users',
                    'choice',
                    [
                        'attr' => ['class' => 'form-control searchUsers'],
                        'multiple' => true,
                        'choices' => $this->getUsersFromRequest(),
                    ]
                );
            }
        );
    }

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

    /**
     * @return array
     */
    private function getUsersFromRequest(): array
    {
        $requestFormData = $this->requestStack->getMasterRequest()->request->get('sso_backendbundle_wsapplicationusers');
        $userIds = is_array($requestFormData['Users']) ? $requestFormData['Users'] : [];
        return array_combine($userIds, $userIds);
    }
}
