<?php

namespace App\Admin;

use App\Entity\Prestataire;
use App\Enum\GroupePrestaEnum;
use App\Form\Type\GeolocFormType;
use FOS\CKEditorBundle\Form\Type\CKEditorType;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\MediaBundle\Form\Type\MediaType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Security\Core\Security;

/**
 * Administration des groupe de prestataires (amap, marche)
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class GroupeprestataireAdmin extends AbstractAdmin
{
    protected $security;
    protected $datagridValues = [
        // reverse order (default = 'ASC')
        '_sort_order' => 'DESC',
        // name of the ordered field (default = the model's id field, if any)
        '_sort_by' => 'updatedAt',
    ];

    public function configure()
    {
        parent::configure();
    }

    public function setSecurity(Security $security)
    {
        $this->security = $security;
    }

    /**
    * {@inheritdoc}
    */
    public function createQuery($context = 'list')
    {
        $user = $this->security->getUser();
        $query = parent::createQuery($context);
        if (empty($this->getRequest()->getSession()->get('_groupegere'))) {
            if ($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT') || $user->isGranted('ROLE_TRESORIER')) {
                $query->andWhere('false = true');
            }
        } else {
            $query
                ->andWhere($query->getRootAliases()[0].'.groupe = :groupe')
                ->setParameter('groupe', $this->getRequest()->getSession()->get('_groupegere'))
            ;
        }
        return $query;
    }


    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $user = $this->security->getUser();
        $groupepresta = $this->getSubject();

        $formMapper
            ->with('Informations', ['class' => 'col-md-7'])
                ->add('type', ChoiceType::class, array(
                    'required' => true,
                    'choices' => GroupePrestaEnum::getAvailableTypes(),
                    'choice_label' => function ($choice) {
                        return GroupePrestaEnum::getTypeName($choice);
                    },
                ))
                ->add('name', TextType::class, array(
                    'label' => 'Nom du groupe :',
                    'required' => true
                ))
        ;
        if (($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT') || $user->isGranted('ROLE_TRESORIER')) && !empty($this->getRequest()->getSession()->get('_groupegere'))) {
            $prestataires = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Prestataire::class)->findByGroupeLocal($this->getRequest()->getSession()->get('_groupegere'));
        } else {
            $prestataires = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Prestataire::class)->findBy(array('enabled' => true, 'mlc' => false), array('raison'=> 'ASC'));
        }
        if ($user->isGranted('ROLE_SUPER_ADMIN') || $user->isGranted('ROLE_ADMIN_SIEGE')) {
            $formMapper
                ->add('groupe', null, array(
                    'label' => 'Groupe local',
                    'required' => true,
                ))
            ;
        }
        $formMapper
                ->add('horaires', CKEditorType::class, array(
                    'label' => 'Horaires :',
                    'required' => false
                ))
                ->add('content', CKEditorType::class, array(
                    'label' => 'Description',
                    'required' => false,
                ))
                ->add('enabled', CheckboxType::class, array(
                    'label' => 'Activé ?',
                    'required' => false,
                    'label_attr' => array('class' => 'checkbox-inline')
                ))
            ->end()
            ->with('Adresse', ['class' => 'col-md-5'])
                ->add('geoloc', GeolocFormType::class, array(
                    'label' => false,
                    'required' => false
                ))
            ->end()
            ->with('Image', ['class' => 'col-md-5'])
                ->add('image', MediaType::class, array(
                    'provider' => 'sonata.media.provider.image',
                    'context' => 'groupe',
                    'label' => 'Image'
                ))
            ->end()
            ->with('Prestataires', ['class' => 'col-md-5'])
            ->add('prestataires', CollectionType::class, array(
                'label' => 'Prestataires',
                'entry_type' => EntityType::class,
                'entry_options' => array(
                    'class' => Prestataire::class,
                    'choices' =>  $prestataires,
                    // 'choice_label' => 'name',
                    'placeholder' => 'Choisir un prestataire',
                    'required' => false,
                    'label' => false),
                'by_reference' => false,
                'allow_add' => true,
                'allow_delete' => true
            ))
        ;
    }

    /**
    * {@inheritdoc}
    */
    protected function configureListFields(ListMapper $listMapper)
    {
        $user = $this->security->getUser();
        unset($this->listModes['mosaic']);
        if ($user->isGranted('ROLE_SUPER_ADMIN') || $user->isGranted('ROLE_ADMIN_SIEGE')) {
            $listMapper
                ->addIdentifier('groupe', null, array(
                    'label' => 'Groupe gestionnaire'
                ))
            ;
        }
        $listMapper
            ->addIdentifier('name', null, array(
                'label' => 'Nom du groupe'
            ))
            ->addIdentifier('type', null, array(
                'label' => 'Type'
            ))
            ->addIdentifier('geoloc', null, array('label' => 'Adresse'))
            ->addIdentifier('horaires', 'html', array(
                'label' => 'Horaires',
                'strip' => true,
                'truncate' => 50
            ))
            ->add('getPrestatairesCount', null, array(
                'label' => 'Nombre de prestas',
                'sortable' => false,
            ))
            ->add('enabled', null, array(
                'label' => 'Activé',
                'editable' => true
            ))
        ;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        parent::configureRoutes($collection);
        $collection->remove('delete');
    }

    public function getBatchActions()
    {
        $actions = parent::getBatchActions();
        unset($actions['delete']);

        return $actions;
    }

    public function getDashboardActions()
    {
        $actions = parent::getDashboardActions();
        unset($actions['list']);
        return $actions;
    }
}