<?php 

namespace NPS\Auth;

use NPS\Model\User;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use NPS\Repository\UserRepository;
use Symfony\Component\Security\Core\Exception\AccountExpiredException;

/**
 * Model user provider
 * @author Lukas Korinek
 */
class UserProvider implements UserProviderInterface
{

    /** @var UserRepository $repo */
    private $repo;

    public function __construct(UserRepository $repo)
    {
        $this->repo = $repo;
    }

    /**
     * Username treated as email
     * @inheritdoc
     */
    public function loadUserByUsername($username)
    {
        $email = (string)$username;
        if($user = $this->repo->getByEmail($email))
        { 
            if(!$user->isActive())
            {
                throw new AccountExpiredException('This account is not active yet');
            }

            if(!$user->getPassword() || !$user->getSalt())
            {
                throw new AccountExpiredException('The password for this user has been reset');
            }

            return $user;
        }
        
        throw new UsernameNotFoundException(
            sprintf('Email "%s" does not exist.', $email)
        );
    }

    /**
     * @inheritdoc
     */
    public function refreshUser(UserInterface $user)
    {
        if (!$user instanceof User) {
            throw new UnsupportedUserException(
                sprintf('Instances of "%s" are not supported.', get_class($user))
            );
        }

        return $this->loadUserByUsername($user->getEmail());
    }

    /**
     * @inheritdoc
     */
    public function supportsClass($class)
    {
        return User::class === $class;
    }
}

