<?php

namespace App\Admin;

use App\Entity\AccountComptoir;
use App\Entity\ContactComptoir;
use App\Entity\Geoloc;
use App\Entity\GlobalParameter;
use App\Enum\CurrencyEnum;
use App\Form\Type\ContactEntityFormType;
use App\Form\Type\GeolocFormType;
use Doctrine\ORM\EntityRepository;
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\DoctrineORMAdminBundle\Filter\CallbackFilter;
use Sonata\MediaBundle\Form\Type\MediaType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Security\Core\Security;

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

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

    /**
     * {@inheritdoc}
     */
    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
        $user = $this->security->getUser();
        // if ($this->hasRequest()) {
        //     if (empty($this->getRequest()->getSession()->get('_groupegere'))) {
        //         if ($this->security->isGranted('ROLE_GESTION_GROUPE') || $this->security->isGranted('ROLE_CONTACT')) {
        //             $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)
    {
        $comptoir = $this->getSubject();
        $user = $this->security->getUser();
        if ($this->isCurrentRoute('create')) {
            $geoloc = new Geoloc();
            $comptoir->setGeoloc($geoloc);
        }
        // get the current Image instance
        $imageHelp = null;
        if (!empty($comptoir) && !empty($comptoir->getMedia())) {
            $image = $comptoir->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" />';
            }
        }
        $formMapper
            ->with('Comptoir', ['class' => 'col-md-6']);
        // if ($user && ($this->security->isGranted('ROLE_GESTION_GROUPE') || $this->security->isGranted('ROLE_CONTACT')) && !empty($this->getRequest()->getSession()->get('_groupegere'))) {
        //     $formMapper->add('groupe', null, [
        //         'label' => 'Groupe local',
        //         'required' => true,
        //         'query_builder' => function (EntityRepository $repo) use ($user) {
        //             return $repo->createQueryBuilder('g')
        //                 ->select('g')
        //                 ->join('g.gestionnaires', 'c')
        //                 ->where('c.id = :user')
        //                 ->setParameter('user', $user->getId());
        //         },
        //     ]);
        // } else {
        $formMapper->add('groupe', null, [
            'label' => 'Groupe local',
            'required' => true,
        ]);
        // }
        $formMapper
                ->add('name', null, [
                    'label' => 'Nom',
                    'required' => true,
                ])
                ->add('content', CKEditorType::class, [
                    'label' => 'Description :',
                    'required' => false,
                ])
                ->add('enabled', null, ['label' => 'Activé ?'])
            ->end()
            ->with('Contact(s)', ['class' => 'col-md-6'])
                ->add('contacts', CollectionType::class, [
                    'entry_type' => ContactEntityFormType::class,
                    'entry_options' => ['label' => false, 'data_class' => ContactComptoir::class],
                    'allow_add' => true,
                    'allow_delete' => true,
                    'by_reference' => false,
                    'label' => false,
                ])
            ->end()
            ->with('Image', ['class' => 'col-md-6'])
                ->add('media', MediaType::class, [
                    'provider' => 'sonata.media.provider.image',
                    'context' => 'prestataire',
                    'help' => $imageHelp,
                    'required' => false,
                ])
            ->end()
            ->with('Geoloc', ['class' => 'col-md-6'])
                ->add('geoloc', GeolocFormType::class, [
                    'label' => false,
                    'required' => true,
                ])
            ->end()
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        if ($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_SUPER_ADMIN') || $this->isGranted('ROLE_ADMIN_SIEGE')) {
            $datagridMapper
                ->add('groupe', null, [
                    'label' => 'Groupe',
                    'show_filter' => true,
                    'advanced_filter' => false,
                ])
            ;
        }
        $datagridMapper
            ->add('full_text', CallbackFilter::class, [
                'callback' => [$this, 'getFullTextFilter'],
                'field_type' => TextType::class,
                'label' => 'Recherche par nom',
                'show_filter' => true,
                'advanced_filter' => false,
            ])
        ;
    }

    public function getFullTextFilter($queryBuilder, $alias, $field, $value)
    {
        if (!$value['value']) {
            return;
        }

        // Use `andWhere` instead of `where` to prevent overriding existing `where` conditions
        $queryBuilder->andWhere(
            $queryBuilder->expr()->like($alias . '.name', $queryBuilder->expr()->literal('%' . $value['value'] . '%'))
        );

        return true;
    }

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

    public function configureActionButtons($action, $object = null)
    {
        $list = parent::configureActionButtons($action, $object);

        $list['test']['template'] = '@kohinos/bundles/SonataAdminBundle/show_map_comptoir.html.twig';

        return $list;
    }

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

    public function getRouteShowMap()
    {
        return $this->routeGenerator->generate('comptoirs_carte');
    }

    /**
     * {@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' => [],
            ];
        } else {
            $actions = [
                'edit' => [],
            ];
        }

        $listMapper
            ->addIdentifier('name')
            ->addIdentifier('groupe', null, [
                'label' => 'Groupe',
                'sortable' => true,
                'sort_field_mapping' => ['fieldName' => 'name'],
                'sort_parent_association_mappings' => [['fieldName' => 'groupe']],
            ])
            ->add('balance', null, ['label' => 'Solde', 'template' => '@kohinos/block/balance.html.twig', 'currency' => 'mlc'])
            ->add('geoloc', null, ['label' => 'Adresse'])
            ->add('enabled', null, [
                'label' => 'Activé',
                'editable' => true,
            ])
            ->add('_action', null, [
                'actions' => $actions,
            ])
        ;
    }

    public function preUpdate($comptoir)
    {
        $this->prePersist($comptoir);
    }

    public function prePersist($comptoir)
    {
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();

        $account = $em->getRepository(AccountComptoir::class)->findOneBy(['comptoir' => $comptoir, 'currency' => CurrencyEnum::CURRENCY_MLC]);
        if (null == $account) {
            $account = new AccountComptoir();
            $account
                ->setCurrency(CurrencyEnum::CURRENCY_MLC)
            ;
            $comptoir->addAccount($account);
            $em->persist($account);
        }
        $em->persist($comptoir);
        $em->flush();
    }

    public function getDataSourceIterator()
    {
        $iterator = parent::getDataSourceIterator();
        $iterator->setDateTimeFormat('d/m/Y H:i:s'); //change this to suit your needs

        return $iterator;
    }

    public function getExportFields()
    {
        return [
            'Id' => 'id',
            'Activé ?' => 'enabled',
            'Nom' => 'name',
            'Groupe local' => 'groupe.name',
            'Adresse' => 'fullAddresse',
            'Contacts' => 'contactsString',
            'Crée le' => 'createdAt',
            'Mise à jour le' => 'updatedAt',
        ];
    }
}
