<?php

namespace App\Repository;

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

/**
 * @extends ServiceEntityRepository<Reference>
 */
class ReferenceRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Reference::class);
    }

    public function findByType(string $type): array
    {
        return $this->createQueryBuilder('r')
            ->andWhere('r.type = :val')
            ->setParameter('val', $type)
            ->getQuery()
            ->getResult();
    }

    public function findHeidelberg(string $ref): array|Reference
    {
        if (substr($ref, 0, 2) == 'ld') {
            $num = substr($ref, 2);
            $qb = $this->createQueryBuilder('r');
            $r = $qb->where($qb->expr()->like('r.label', ':ld'))
                ->setParameter('ld', "LD{$num}-%")
                ->getQuery()
                ->getResult()
            ;
        } elseif (substr($ref, 0, 2) == 'hc') {
            $num = substr($ref, 2);
            $qb = $this->createQueryBuilder('r');
            $r = $qb->where($qb->expr()->like('r.label', ':hc'))
                ->setParameter('hc', "%-HC{$num}")
                ->getQuery()
                ->getResult()
            ;

            if(count($r) > 0) {
                $r = $r[0];

                $r->setLabel(implode("\n", explode("-", $r->getLabel())));
            }
        }

        return $r;
    }

    //    /**
    //     * @return Reference[] Returns an array of Reference objects
    //     */
    //    public function findByExampleField($value): array
    //    {
    //        return $this->createQueryBuilder('r')
    //            ->andWhere('r.exampleField = :val')
    //            ->setParameter('val', $value)
    //            ->orderBy('r.id', 'ASC')
    //            ->setMaxResults(10)
    //            ->getQuery()
    //            ->getResult()
    //        ;
    //    }

    //    public function findOneBySomeField($value): ?Reference
    //    {
    //        return $this->createQueryBuilder('r')
    //            ->andWhere('r.exampleField = :val')
    //            ->setParameter('val', $value)
    //            ->getQuery()
    //            ->getOneOrNullResult()
    //        ;
    //    }
}
