<?php

namespace App\Repository;

use App\Entity\Product;
use DateTime;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<Product>
 *
 * @method Product|null find($id, $lockMode = null, $lockVersion = null)
 * @method Product|null findOneBy(array $criteria, array $orderBy = null)
 * @method Product[]    findAll()
 * @method Product[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class ProductRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Product::class);
    }

    private $batch = [];

    public function save(Product $entity, bool $flush = false): ?int
    {

        $entity->setUpdateTime(new DateTime());

        $this->getEntityManager()->persist($entity);

        if ($flush) {
            $this->getEntityManager()->flush();
        }

        return $entity->getId();
    }

    public function remove(Product $entity, bool $flush = false): void
    {
        $this->getEntityManager()->remove($entity);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }

    /**
     * @return Product[] Returns an array of Product objects
     */
    public function findById($value): array
    {
        return $this->createQueryBuilder('p')
            ->andWhere('p.id IN (:val)')
            ->setParameter('val', $value)
            ->getQuery()
            ->getResult();
    }

    public function add(Product $product): void
    {
        $this->batch[] = $product;
    }

    public function saveAll(): array
    {
        $product_ids = [];

        foreach ($this->batch as $product) {
            $product->setUpdateTime(new DateTime());
            $this->getEntityManager()->persist($product);
            $product_ids[] = $product->getId();
        }
        $this->getEntityManager()->flush();
        return $product_ids;
    }

}