<?php

namespace Webkul\WooCommerceBundle\Repository;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;


/**
 * @author    Webkul Software Pvt Ltd
 * @copyright  Webkul Software Pvt Ltd (https://www.webkul.com)
 */
class WoocommerceExportMappingRepository extends EntityRepository implements \DatagridRepositoryInterface, \MassActionRepositoryInterface
{
    /** @var EntityManager */
    protected $em;

    /** @var string */
    protected $entityName;

    /**
     * @param EntityManager $em
     * @param string        $class
     */
    public function __construct(EntityManager $em, $class)
    {
        parent::__construct($em, $em->getClassMetadata($class));

        $this->em = $em;
        $this->entityName = $class;
    }

    /**
     * {@inheritdoc}
     */
    public function createDatagridQueryBuilder()
    {
        $qb = $this->createQueryBuilder('wem');

        return $qb;
    }

    /**
     * {@inheritdoc}
     *
     * @param QueryBuilder $queryBuilder
     */
    public function applyMassActionParameters($qb, $inset, array $values)
    {
        // if (!empty($values)) {
        //     $condition = $inset ? Operators::IN_LIST : Operators::NOT_IN_LIST;
        //     $queryBuilder->where('wem.id '. $condition . ' (:values)');
        //     $queryBuilder->setParameter('values', $values);
        // }
        if ($values) {
            $rootAlias = $qb->getRootAlias();
            $valueWhereCondition =
                $inset
                    ? $qb->expr()->in($rootAlias, $values)
                    : $qb->expr()->notIn($rootAlias, $values);
            $qb->andWhere($valueWhereCondition);
        }

        if (null !== $qb->getDQLPart('where')) {
            $whereParts = $qb->getDQLPart('where')->getParts();
            $qb->resetDQLPart('where');

            foreach ($whereParts as $part) {
                if (!is_string($part) || !strpos($part, 'entityIds')) {
                    $qb->andWhere($part);
                }
            }
        }

        $qb->setParameters(
            $qb->getParameters()->filter(
                function ($parameter) {
                    return $parameter->getName() !== 'entityIds';
                }
            )
        );
    }

    // /**
    //  * {@inheritdoc}
    //  */
    // public function deleteFromIds(array $identifiers)
    // {
    //     if (empty($identifiers)) {
    //         throw new \LogicException('No mappings to remove');
    //     }

    //     $qb = $this->em->createQueryBuilder();
    //     $qb->delete($this->entityName, 'wem')
    //         ->where($qb->expr()->in('wem.id', $identifiers));

    //     return $qb->getQuery()->execute();
    // }
}
