<?php

namespace App\Repository;

use App\Entity\WebrootUser;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;

/**
 * @extends ServiceEntityRepository<WebrootUser>
 */
class WebrootUserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, WebrootUser::class);
    }

    /**
     * Used to upgrade (rehash) the user's password automatically over time.
     */
    public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
    {
        if (!$user instanceof WebrootUser) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $user::class));
        }

        $user->setPassword($newHashedPassword);
        $this->getEntityManager()->persist($user);
        $this->getEntityManager()->flush();
    }

    public function getAdministrators(): array
    {
        return $this->createQueryBuilder('w')
                ->andWhere('w.is_admin = :val')
                ->setParameter('val', true)
                ->orderBy('w.name','ASC')
                ->getQuery()
                ->getResult();
    }
    
    public function hasAdministrator(): array
    {
        return (count(
                $this->createQueryBuilder('w')
                ->andWhere('w.is_admin = :val')
                ->setParameter('val', true)
                ->setMaxResults(1)
                ->getQuery()
                ->getResult()                
        ) > 0);
    }
    
    public function findByUsername($username): ?WebrootUser
    {
        return $this->createQueryBuilder("w")
                ->andWhere('w.username = :val')
                ->setParameter('val', $username)
                ->getQuery()
                ->getOneOrNullResult();
    }
    
    public function findByEmail($email): ?WebrootUser
    {
        return $this->createQueryBuilder("w")
                ->andWhere('w.email = :val')
                ->setParameter('val', $email)
                ->getQuery()
                ->getOneOrNullResult();
    }
    
    //    public function findOneBySomeField($value): ?WebrootUser
    //    {
    //        return $this->createQueryBuilder('w')
    //            ->andWhere('w.exampleField = :val')
    //            ->setParameter('val', $value)
    //            ->getQuery()
    //            ->getOneOrNullResult()
    //        ;
    //    }
}
