<?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 ItemPackageItemForm extends AbstractType
{
    private $manager;

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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', HiddenType::class)
            ->add('item', TextType::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));

    }

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

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' 	  => 'RxConnexionBundle\Entity\ItemPackageItemEntity',
        ));
    }
}