<?php

namespace Lc\SovBundle\Field\Filter;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
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())
    {
        $targetEntity = $options['entity_dto']->getPropertyMetadata($fieldDto->getProperty())->get('targetEntity');

        $classImplements = class_implements($targetEntity);
        $builder->add(
                $fieldDto->getProperty(),
                EntityType::class,
                array(
                        'class' => $targetEntity,
                        'placeholder' => '--',
                        'query_builder' => function (EntityRepository $repo) use ($classImplements) {
                            return $repo->createQueryBuilder('entity');
                        },
                        'required' => false,
                        'attr' => array(
                                'class' => 'select2 input-sm',
                                'form' => 'filters-form',
                        ),


                )
        );
    }

    public function applyFilter(QueryBuilder $queryBuilder, string $fieldProperty, string $filteredValue = null)
    {
        if ($filteredValue !== null) {
            $queryBuilder->andWhere('entity.'.$fieldProperty.' = :'.$fieldProperty.'');
            $queryBuilder->setParameter($fieldProperty, $filteredValue);
            /*    //TODO Faut généraliser avec TreeInterface, ça ne doit pas être ici
                if ($field['property'] == 'productCategories') {

                    $queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'] . ' OR product_categories.parent = :' . $field['property']);
                    $queryBuilder->setParameter($field['property'], $filter);

                if ($field['type_options']['multiple']) {
                    $queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'] . '');
                } else {
                }

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

}
