<?php

namespace App\Repository;

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

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

    public function add(UserAddress $entity, bool $flush = false): void
    {
        $this->getEntityManager()->persist($entity);

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

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

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

    public function addressByUser($idUser)
    {
        $query = $this->createQueryBuilder('a')
            ->select('a.id, a.name, a.street, a.houseNumber, a.apartment, a.postalCode,
                a.latitude, a.longitude, a.updatedAt')
            ->leftJoin(
                User::class,
                'u',
                \Doctrine\ORM\Query\Expr\Join::WITH,
                'u.id = a.user'
            )
            ->andWhere('u.id = :user')
            ->setParameter(':user', $idUser)
            ->orderBy('a.updatedAt', 'desc')
            ->getQuery()
            ->getArrayResult()
        ;
        return $query;
    }

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

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