<?php

namespace App\Repository;

use App\Entity\User;
use App\Entity\Notification;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;

/**
 * @method Notification|null find($id, $lockMode = null, $lockVersion = null)
 * @method Notification|null findOneBy(array $criteria, array $orderBy = null)
 * @method Notification[]    findAll()
 * @method Notification[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class NotificationRepository extends ServiceEntityRepository
{
    private array $fields = [];
    private QueryBuilder $qb;
    private ?User $user = null;

    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Notification::class);
    }

    /**
     * Equivalent of FindAll()
     *     *
     * @return QueryBuilder
     */
    private function getQueryBuilder()
    {
        return $this->createQueryBuilder("n");
        ;
    }

    public function listForUser(User $User)
    {
        $this->user = $User;
        $this->qb = $this   ->getQueryBuilder()
                            ->where('n.receiver = :userid')
                            ->setParameter('userid', $User->getId());
        return $this;
    }

    public function limit(int $limit)
    {
        $this->qb->setMaxResults($limit);
        return $this;
    }

    public function readed(bool $readed = true)
    {
        if (true === $readed) {
            $this->qb->andWhere('n.readed = 1');
        } else {
            $this->qb->andWhere('n.readed = 0');
        }
        return $this;
    }

    public function order(array $order)
    {
        foreach ($order as $key => $value) {
            if ($key === array_key_first($order)) {
                $this->qb->orderBy('n.' . $key, $value);
            } else {
                $this->qb->addorderBy('n.' . $key, $value);
            }
        }
        return $this;
    }

    public function getResult()
    {
        return $this->qb->getQuery()->getResult();
    }

    public function getCount()
    {
        $this->qb->select('count(n.id)');
        return $this->qb->getQuery()->getSingleScalarResult();
    }
}
