<?php

namespace App\Repository;

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

/**
 * @method Group|null find($id, $lockMode = null, $lockVersion = null)
 * @method Group|null findOneBy(array $criteria, array $orderBy = null)
 * @method Group[]    findAll()
 * @method Group[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class GroupRepository extends ServiceEntityRepository
{
    private QueryBuilder $qb;
    private array $order = ['name' => 'ASC', 'shortName' => 'ASC', 'createdAt' => 'ASC'];

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

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

    public function getAll()
    {
        $this->qb = $this->getQueryBuilder();
        return $this;
    }

    public function order(array $order)
    {
        $this->order = $order;
        return $this;
    }

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

    public function search(?string $search)
    {
        if (null === $search) {
            return $this;
        }

        $this->qb   ->where('g.name LIKE :searchkey')
                    ->orWhere('g.shortName LIKE :searchkey')
                    ->setParameter('searchkey', '%' . $search . '%')
                ;



        $this->qb->setParameter('searchkey', '%' . $search . '%');

        return $this;
    }

    public function getResult()
    {
        if (false === is_null($this->order)) {
            foreach ($this->order as $key => $value) {
                if (strtoupper($value) != 'ASC' && strtoupper($value) != 'DESC') {
                    $key = $value;
                    $value = 'ASC';
                }
                if ($key === array_key_first($this->order)) {
                    $this->qb->orderBy('g.' . $key, $value);
                } else {
                    $this->qb->addorderBy('g.' . $key, $value);
                }
            }
        }

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