<?php
namespace EmotionHero\Models;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class UserRepository extends EntityRepository implements UserProviderInterface
{

    /**
     * Loads the user for the given username.
     *
     * This method must throw UsernameNotFoundException if the user is not
     * found.
     *
     * @param string $username The username
     *
     * @return UserInterface
     *
     * @throws UsernameNotFoundException if the user is not found
     */
    public function loadUserByUsername($username) {
    	$user = $this->find($username); // username == $id field
    	if(!$user) {
    		throw new \Symfony\Component\Security\Core\Exception\UsernameNotFoundException("Invalid username");
    	}
    	return $user;
    }

    /**
     * Refreshes the user for the account interface.
     *
     * It is up to the implementation to decide if the user data should be
     * totally reloaded (e.g. from the database), or if the UserInterface
     * object can just be merged into some internal array of users / identity
     * map.
     *
     * @param UserInterface $user
     *
     * @return UserInterface
     *
     * @throws UnsupportedUserException if the account is not supported
     */
    public function refreshUser(UserInterface $user) {
    	$this->_em->refresh($user);
    }

    /**
     * Whether this provider supports the given user class.
     *
     * @param string $class
     * @todo Extending User should be possible
     * @return bool
     */
    public function supportsClass($class) {
    	return $class == User::class;
    }
    
    public function updateTotalForUser(User $user) {
        $query = $this->_em->createQuery(
         "SELECT MAX(g.score) as score FROM ".Game::class." g INNER JOIN g.level l INNER JOIN g.user u WHERE g.user = :user GROUP BY g.level"
         )
         ->setParameters([
             'user' => $user,
         ]);
        $results = $query->getScalarResult();
        $score = 0;
        foreach($results as $result) {
            $score += $result['score'];
        }
        
        $user->setTotalScore($score);
        $this->_em->persist($user);
        $this->_em->flush($user);
        
        return $score;
    }

    /**
     * @param \EmotionHero\Models\User $user
     * @return integer
     */
    public function getRankForUser(User $user)  {
       
        $query = $this->_em->createQuery(
         "SELECT COUNT(u.id) FROM ".User::class." u WHERE u.totalScore >= :totalScore"
         )
         ->setParameters([
             'totalScore' => $user->getTotalScore(),
         ]);
        return (int) $query->getSingleScalarResult(); 
    }
}