<?php

namespace App\Admin;

use App\Entity\Prestataire;
use App\Enum\GroupePrestaEnum;
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)
 *
 * LOCO : 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 ($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT')) {
            if (empty($user->getGroupesgere())) {
                $query->andWhere('false');
            } else {
                $query
                    ->andWhere($query->getRootAliases()[0].'.groupe = :groupe')
                    ->setParameter('groupe', $user->getGroupesgere())
                ;
            }
        }
        // dump($query->getQuery());
        // exit();
        return $query;
    }


    /**
    * {@inheritdoc}
    */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $user = $this->security->getUser();
        $prestataires = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Prestataire::class)->findBy(array('enabled' => true), array('raison'=> 'ASC'));
        $groupepresta = $this->getSubject();
        if ($this->isCurrentRoute('create') && $user->getGroupesgere() != null) {
            $groupepresta->setGroupe($user->getGroupesgere());
        }
        $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')) && $this->security->getUser()->getGroupesgere() != null) {
            $prestataires = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Prestataire::class)->findBy(array('enabled' => true, 'groupe' => $this->security->getUser()->getGroupesgere()), 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' => 'Texte',
                    'required' => false,
                ))
                ->add('enabled', CheckboxType::class, array(
                    'label' => 'Activé ?',
                    'required' => false,
                    'label_attr' => array('class' => 'checkbox-inline')
                ))
            ->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('horaires', 'html', array(
                'label' => 'Horaires',
                'strip' => true,
                'truncate' => 50
            ))
            ->add(
                'getPrestatairesCount',
                null,
                [
                    'sortable' => true,
                    'sort_field_mapping' => ['fieldName' => 'id'],
                    'sort_parent_association_mappings' => [],
                ]
            )
            ->addIdentifier('enabled', null, array(
                'label' => 'Activé',
                'datatype' => 'App.Groupeprestataire',
                'template' => '@SonataAdmin/Boolean/editable_boolean.html.twig'
            ))
        ;
    }

    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;
    }

    // @TODO : NE FONCTIONNE PAS : pour pouvoir classer par nombre de prestataires !
    // voir https://github.com/sonata-project/SonataDoctrineORMAdminBundle/issues/297
    // public function createQuery($context = 'list')
    // {
    //     $query = parent::createQuery($context);
    //     if ('list' === $context) {
    //         $rootAlias = $query->getRootAliases()[0];
    //         $parameters = $this->getFilterParameters();
    //         if ('getPrestatairesCount' === $parameters['_sort_by']) {
    //             $query->select('o', 'DISTINCT o');
    //             $query
    //                 ->leftJoin($rootAlias.'.prestataires', 'gpr')
    //                 // ->leftJoin('groupes_prestataires.prestataires', 'pr')
    //                 ->groupBy($rootAlias.'.id')
    //                 ->orderBy('COUNT(gpr.id)', $parameters['_sort_order'])
    //             ;
    //         }
    //     }
    //     return $query;
    // }
}
