<?php
namespace Backend\BaseBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\Tag;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\Options;
use Backend\BaseBundle\Model;
use Propel\Bundle\PropelBundle\Form\Type\ModelType;

/**
 * @Service
 * @Tag("form.type", attributes = {"alias": "relation"})
 */
class RelationType extends AbstractType
{
    /** @var  Session */
    protected $session;

    /**
     * @InjectParams
     */
    public function injectService(Session $session)
    {
        $this->session = $session;
    }


    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if(is_callable($options['preSetData'])) {
            $builder->addEventListener(FormEvents::PRE_SET_DATA, $options['preSetData']);
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'multiple' => true,
            'query' => function(Options $options){
                $queryClass = $options['class'].'Query';
                return $queryClass::create()
                    ->filterBySiteId($this->session->get('Site')->getId());
            },
            'preSetData' => null,
        ));
    }

    public function getParent()
    {
        return ModelType::class;
    }

}