<?php

namespace Webkul\ShopifyBundle\Repository;

/**
 * DataMappingRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class DataMappingRepository extends \Doctrine\ORM\EntityRepository
{
    public function __construct($em, $class)
    {
        parent::__construct($em, $em->getClassMetadata($class));
        $this->em = $em;
        $this->entityName = $class;
    }

    /**
    * {@inheritdoc}
    */
    public function createDatagridQueryBuilder()
    {
        $qb = $this->createQueryBuilder('aem');

        return $qb;
    }

    /**
     * {@inheritdoc}
     *
     * @param QueryBuilder $queryBuilder
     */
    public function applyMassActionParameters($qb, $inset, array $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, 'aem')
            ->where($qb->expr()->in('aem.id', $identifiers));

        return $qb->getQuery()->execute();
    }
}
