<?php

namespace Lc\SovBundle\Field\Filter;

use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use Lc\SovBundle\Translation\TranslatorAdmin;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;

use function Symfony\Component\String\u;


/**
 * @author La clic ! <contact@laclic.fr>
 */
class ChoiceFilter
{
    use FilterTrait;

    protected $translatorAdmin;

    public function __construct(?TranslatorAdmin $translatorAdmin = null)
    {
        $this->translatorAdmin = $translatorAdmin;
    }

    public function buildProperty(FormBuilderInterface $builder, FieldDto $fieldDto, $options = array())
    {
        $entity = new $options['entity_class'];
        $choicesFct = 'get'.u($fieldDto->getProperty())->title()->toString().'Choices';

        if (method_exists($entity, $choicesFct)) {
            $builder->add(
                    $fieldDto->getProperty(),
                    ChoiceType::class,
                    array(
                            'required' => false,
                            'choices' => $this->translatorAdmin->transChoices(
                                    $entity->$choicesFct(),
                                    $options['entity_name'],
                                    $fieldDto->getProperty()
                            ),
                            'attr' => array(
                                    'class' => 'select2 input-sm',
                                    'form' => 'filters-form',
                            ),
                    )
            );
        }
    }

    public function applyFilter(QueryBuilder $queryBuilder, string $fieldProperty, string $filteredValue = null)
    {
        if ($filteredValue !== null) {
            if ($this->isRelationField($fieldProperty)) {
                $aliasRelation = $this->getFieldPropertyRelationAlias($fieldProperty);
                if (array_search($aliasRelation, $queryBuilder->getAllAliases()) === false) {
                    $queryBuilder->innerJoin('entity.'.$aliasRelation, $aliasRelation);
                }
                $queryBuilder->andWhere(
                        $fieldProperty.' LIKE :'.$this->getFieldPropertySnake($fieldProperty).''
                );
                $queryBuilder->setParameter(
                        $this->getFieldPropertySnake($fieldProperty),
                        '%'.$filteredValue.'%'
                );
            } else {
                $queryBuilder->andWhere(
                        'entity.'.$fieldProperty.' LIKE :'.$fieldProperty.''
                );
                $queryBuilder->setParameter($fieldProperty, '%'.$filteredValue.'%');
            }
        }
    }

}
