<?php

/*
 * kohinos_cooperatic
 * Copyright (C) 2019-2020  ADML63
 * Copyright (C) 2020- Cooperatic
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
namespace App\Admin;

use App\Entity\Comptoir;
use App\Entity\GlobalParameter;
use App\Entity\Prestataire;
use App\Entity\Siege;
use App\Entity\Rubrique;
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\AdminBundle\Show\ShowMapper;
use Sonata\MediaBundle\Form\Type\MediaType;
use Sonata\MediaBundle\Provider\Pool;
use Sonata\MediaBundle\Provider\MediaProviderInterface;
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\HiddenType;
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)->findBy(array('enabled' => true, 'mlc' => false), array('raison'=> 'ASC'));

        // 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, array(
                    'label' => 'Nom :',
                    'required' => true
                ))
                ->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('Image', ['class' => 'col-md-6'])
                ->add('media', MediaType::class, array(
                    'provider' => 'sonata.media.provider.image',
                    'context' => 'rubrique',
                    // 'help' => $imageHelp,
                    'label' => false,
                    'required' => false
                ))
            ->end()
            ->with('Prestataires', ['class' => 'col-md-6'])
                ->add('prestataires', CollectionType::class, array(
                    'label' => false,
                    '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
                ))
            ->end()
        ;
    }

    public function getRouteShowOnFront($object)
    {
        return $this->routeGenerator->generate('show_rubrique', array('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 ($isWordpressActivated == 'false') {
            $actions = [
                'show' => ['template' => '@SonataAdmin/CRUD/list__action_showonfront.html.twig'],
                'edit' => [],
                'delete' => [],
            ];
        } else {
            $actions = [
                'edit' => [],
                'delete' => [],
            ];
        }
        $listMapper
            ->add('file', null, array('label' => 'Icône', 'template' => '@SonataAdmin/Image/preview_image_o.html.twig'))
            ->add('name', null, array('editable' => true, 'truncate' => array('length' => 80), 'label' => 'Nom du groupe'))
            ->add('content', 'html', array('truncate' => array('length' => 80), 'label' => 'Description'))
            ->add('getPrestatairesCount', null, array(
                    'label' => 'Nombre de prestas',
                    'sortable' => false
            ))
            ->add('enabled', null, array(
                'label' => 'Activé',
                'editable' => true
            ))
            ->add('_action', null, [
                'actions' => $actions
            ])
        ;
    }
}
