<?php

namespace Cadoles\PortalBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\EntityManager;

class BlogWriterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $id=$options['id'];
        $access=$options['access'];

        $builder
            ->add('submit', SubmitType::class, [
                "label"         => ($options["mode"]=="delete"?"Confirmer la Suppression":"Valider"),
                "attr"          => ($options["mode"]=="delete"?array("class" => "btn btn-danger"):array("class" => "btn btn-success"))
            ])

            ->add('writers', EntityType::class, [
                'label'         => 'Donner permissions en écritures à',
                'class'         => 'CadolesCoreBundle:User',
                'query_builder' => function(EntityRepository $er) use ($id,$access) {
                    $qb= $er->createQueryBuilder('user');
                    return $qb->select('user')

                            ->from('CadolesPortalBundle:Blog','blog')
                            ->andwhere('blog.id=:blog')

                            ->from('CadolesCoreBundle:UserGroup','usergroup')
                            ->andwhere("usergroup.group MEMBER OF blog.groups")
                            ->andwhere("usergroup.user=user")

                            ->setParameter('blog',$id);
                },
                'choice_label'  => 'username',
                'multiple'      => true,
                'expanded'      => true
            ]);
            
            ;   

    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'Cadoles\PortalBundle\Entity\Blog',
            'id' => 'integer',
            'mode' => 'string',
            'access' => 'string',
            'user' => 'Cadoles\CoreBundle\Entity\User'
        ]);
    }
}
