<?php

namespace App\Admin;

use App\Entity\GlobalParameter;
use App\Entity\Prestataire;
use FOS\CKEditorBundle\Form\Type\CKEditorType;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
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\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Security\Core\Security;

/**
 * Administration des rubriques.
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 *
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class RubriqueAdmin extends AbstractAdmin
{
    protected $security;
    protected $datagridValues = [
        '_sort_order' => 'ASC',
        '_sort_by' => 'name',
    ];

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

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

    /**
     * {@inheritdoc}
     */
    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
        $query
            ->leftJoin($query->getRootAliases()[0] . '.media', 'm')
            ->addSelect('m')
        ;

        return $query;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $rubrique = $this->getSubject();
        $user = $this->security->getUser();
        $prestataires = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Prestataire::class)->findDefault();

        // get the current Image instance
        $imageHelp = null;
        if (!empty($rubrique) && !empty($rubrique->getMedia())) {
            $image = $rubrique->getMedia();
            if ($image && ($webPath = $image->getWebPath())) {
                // get the container so the full path to the image can be set
                $container = $this->getConfigurationPool()->getContainer();
                $fullPath = $container->get('request_stack')->getCurrentRequest()->getBasePath() . '/' . $webPath;
                // add a 'help' option containing the preview's img tag
                $imageHelp = '<img src="' . $fullPath . '" class="admin-preview" />';
            }
        }

        $groupe = $this->getSubject();
        $formMapper
            ->with('Contenu', ['class' => 'col-md-6'])
                ->add('name', TextType::class, [
                    'label' => 'Nom :',
                    'required' => true,
                ])
                ->add('content', CKEditorType::class, [
                    'label' => 'Description :',
                    'required' => false,
                ])
                ->add('enabled', CheckboxType::class, [
                    'label' => 'Activé ?',
                    'required' => false,
                    'label_attr' => ['class' => 'checkbox-inline'],
                ])
                ->add('isPrestaMapFilter', CheckboxType::class, [
                    'label' => 'Est un filtre de la carte des Points de vente ?',
                    'required' => false,
                    'label_attr' => ['class' => 'checkbox-inline'],
                ])
            ->end()
            ->with('Image', ['class' => 'col-md-6'])
                ->add('media', MediaType::class, [
                    'provider' => 'sonata.media.provider.image',
                    'context' => 'rubrique',
                    // 'help' => $imageHelp,
                    'label' => false,
                    'required' => false,
                ])
            ->end()
            ->with('Prestataires', ['class' => 'col-md-6'])
                ->add('prestataires', CollectionType::class, [
                    'label' => false,
                    'entry_type' => EntityType::class,
                    'entry_options' => [
                        '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,
                ])
            ->end()
        ;
    }

    public function getRouteShowOnFront($object)
    {
        return $this->routeGenerator->generate('show_rubrique', ['slug' => $object->getSlug()]);
    }

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

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        unset($this->listModes['mosaic']);
        $isWordpressActivated = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_WORDPRESS);
        if ('false' == $isWordpressActivated) {
            $actions = [
                'show' => ['template' => '@kohinos/bundles/SonataAdminBundle/CRUD/list__action_showonfront.html.twig'],
                'edit' => [],
                'delete' => [],
            ];
        } else {
            $actions = [
                'edit' => [],
                'delete' => [],
            ];
        }
        $listMapper
            ->add('file', null, ['label' => 'Icône', 'template' => '@kohinos/bundles/SonataAdminBundle/Image/preview_image_o.html.twig'])
            ->add('name', null, ['editable' => true, 'truncate' => ['length' => 80], 'label' => 'Nom du groupe'])
            ->add('content', 'html', ['truncate' => ['length' => 80], 'label' => 'Description'])
            ->add('getPrestatairesCount', null, [
                'label' => 'Nombre de prestas',
                'sortable' => false,
            ])
            ->add('enabled', null, [
                'label' => 'Activé',
                'editable' => true,
            ])
            ->add('_action', null, [
                'actions' => $actions,
            ])
        ;
    }
}
