<?php

namespace Lc\SovBundle\Field\Filter;

use Doctrine\ORM\EntityRepository;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use Lc\SovBundle\Repository\RepositoryQueryInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

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


    public function buildProperty(FormBuilderInterface $builder, FieldDto $fieldDto, $options = array())
    {
        $param = array();
        $targetEntity = $options['entity_dto']->getPropertyMetadata($fieldDto->getProperty())->get('targetEntity');

        if ($fieldDto->getCustomOption('choices')) {
            $choices = $fieldDto->getCustomOption('choices');
        } elseif ($fieldDto->getFormTypeOption('choices') != null) {
            $choices = $fieldDto->getFormTypeOption('choices');
        } else {
            $choices = array();
        }

        if ($fieldDto->getFormTypeOption('choice_label') != null) {
            $param['choice_label'] = $fieldDto->getFormTypeOption('choice_label');
        }
        //todo utiliser choices plutot que query_builder voir ProductCategoriesFilter
        $builder->add(
                $fieldDto->getProperty(),
                EntityType::class,
                array_merge(
                        $param,
                        array(
                                'class' => $targetEntity,
                                'placeholder' => '--',
                                'choices' => $choices,
                                'required' => false,
                                'attr' => array(
                                        'class' => 'select2 input-sm',
                                        'form' => 'filters-form',
                                ),


                        )
                )
        );
    }

    public function applyFilter(RepositoryQueryInterface $repositoryQuery, FieldDto $fieldDto, $filteredValue = null)
    {
        $fieldProperty = $this->getFieldProperty($fieldDto);

        if ($filteredValue !== null) {
            if ($fieldDto->getFormTypeOption('multiple') || ($fieldDto->getTemplatePath() != null && str_contains($fieldDto->getTemplatePath(), 'association_many'))) {
                $repositoryQuery->andWhere(':' . $fieldProperty . ' MEMBER OF .' . $fieldProperty . '');
            } else {
                $repositoryQuery->andWhere('.' . $fieldProperty . ' = :' . $fieldProperty . '');
            }
            $repositoryQuery->setParameter($fieldProperty, $filteredValue);


//
//                if ($filter instanceof TreeInterface && $filter->getParent() == null) {
//                    $repositoryQuery->setParameter($field['property'], array_merge(array($filter), $filter->getChildrens()->toArray()));
//                } else {
//                }
        }
    }

}