<?php

namespace App\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\DoctrineORMAdminBundle\Filter\CallbackFilter;
use Sonata\Form\Type\DateTimeRangePickerType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * Administration des opérations.
 *
 * KOHINOS : Outil de gestion de Monnaie Locale Complémentaire
 *
 * @author Julien Jorry <julien.jorry@gmail.com>
 */
class OperationAdmin extends AbstractAdmin
{
    protected $translator;
    protected $security;
    protected $datagridValues = [
        '_sort_order' => 'DESC',
        '_sort_by' => 'createdAt',
        '_per_page' => 250,
    ];
    protected $maxPerPage = 250;
    protected $perPageOptions = [50, 100, 250, 500, 1000];

    public function setTranslator(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

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

    /**
     * {@inheritdoc}
     */
    protected function configureRoutes(RouteCollection $collection)
    {
        $collection->clearExcept(['list', 'export']);
    }

    public function getExportFields()
    {
        return [
            'Date' => 'createdAt',
            'Montant' => 'montant',
            'Compte' => 'currency',
            'Type' => 'flux.type',
            'Moyen' => 'flux.moyen',
            'Operateur' => 'flux.operateur',
            'Importé' => 'historical',
        ];
    }

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

        return $iterator;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        unset($this->listModes['mosaic']);
        $listMapper
            ->add('montant', 'decimal', ['label' => 'Montant', 'attributes' => ['fraction_digits' => 2]])
            ->add('currency', null, ['label' => 'Devise'])
            ->add('flux.expediteur', null, ['label' => 'Expediteur', 'template' => '@kohinos/bundles/SonataAdminBundle/Block/accountable.html.twig'])
            // ->add('flux.destinataire', null, ['label' => 'Destinataire', 'template' => '@kohinos/bundles/SonataAdminBundle/Block/accountable.html.twig'])
            // ->add('account.accountableObject', null, ['label' => 'Compte'])
            ->add('flux.type', 'text', ['label' => 'Type', 'template' => '@kohinos/bundles/SonataAdminBundle/Block/translated_value.html.twig'])
            ->add('flux.operateur', null, ['label' => 'Operateur'])
            ->add('flux.reference', null, ['label' => 'Reference'])
            ->add('createdAt', 'datetime', ['label' => 'Date'])
        ;
        if ($listMapper->getAdmin()->getRequest()->query->has('filter') &&
            isset($listMapper->getAdmin()->getRequest()->query->get('filter')['show_verify']['value']) &&
            true == $listMapper->getAdmin()->getRequest()->query->get('filter')['show_verify']['value']
            ) {
            $listMapper->addIdentifier('flux.verify', null, ['label' => 'Vérifié']);
        }
    }

    // public function getTemplate($name)
    // {
    //     if ('list' == $name) {
    //         return '@kohinos/block/base_list_with_total.html.twig';
    //     }

    //     return parent::getTemplate($name);
    // }

    // public function getTotalLabel()
    // {
    //     return $this->translator->trans('Total des opérations');
    // }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        parent::configureDatagridFilters($datagridMapper);
        $datagridMapper
            ->add('show_verify', CallbackFilter::class, [
                'label' => 'Vérifier la validité des flux',
                'advanced_filter' => false,
                'show_filter' => false,
                'field_type' => CheckboxType::class,
                'callback' => static function (ProxyQueryInterface $query, string $alias, string $field, array $data): bool {
                    if (!$data['value']) {
                        return false;
                    }

                    return true;
                },
            ])
            ->add('createdAt', 'doctrine_orm_datetime_range', [
                'field_type' => DateTimeRangePickerType::class,
                'label' => 'Date',
            ])
        ;
    }

    // public function getTotal()
    // {
    //     $datagrid = $this->getDatagrid();
    //     $datagrid->buildPager();

    //     $query = clone $datagrid->getQuery();
    //     $query
    //         ->select('SUM( ' . $query->getRootAlias() . '.montant) as total')
    //         ->setFirstResult(null)
    //         ->setMaxResults(null);

    //     $result = $query->execute([], \Doctrine\ORM\Query::HYDRATE_SINGLE_SCALAR);

    //     return $result;
    // }
}
