<?php

namespace Lc\SovBundle\Field\Filter;

use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

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


    public function buildProperty(FormBuilderInterface $builder, FieldDto $fieldDto,  $options = array())
    {
        $builder->add(
                str_replace('.', '_', $fieldDto->getProperty()),
                TextType::class,
                array(
                        'required' => false,
                        'attr' => array(
                                'class' => ' 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.'%');
            }
        }
    }

}
