<?php

namespace RxConnexionBundle\Form\Type;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use RxConnexionBundle\Form\DataTransformer\DataTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ItemItemForm extends AbstractType
{
    private $manager;

    public function __construct(ObjectManager $manager) {
        $this->manager = $manager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('action', HiddenType::class, array(
                'mapped' => false,
                'attr' => array(
                    'class' => 'form-action'
                )
            ))
            ->add('id', HiddenType::class)
            ->add('item', HiddenType::class)
            ->add('mainItem', HiddenType::class)
            ->addEventListener(FormEvents::PRE_SET_DATA,function (FormEvent $event) use ($builder) {
                $form = $event->getForm();
                $data = $event->getData();

                $form
                    ->add('item_description', TextType::class, array(
                        'mapped' => false,
                        'required' => true,
                        'data' => $data && $data->getItem() ? $data->getItem()->getDescription() : ''
                    ));
            });
        $builder->get('item')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ItemEntity', false));
        $builder->get('mainItem')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ItemEntity'));

    }

    public function getBlockPrefix()
    {
        return 'itemItem';
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' 	  => 'RxConnexionBundle\Entity\ItemItemEntity',
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            // a unique key to help generate the secret token
            'intention'       => 'itemItemEntity_intention',
            'action'          => 'n'
        ));
    }
}