<?php

namespace Application\Model\Manager;

use Ainias\Core\Model\Manager\StandardManager;
use Application\Model\Repository\AuthTokenRepository;
use Application\Model\AuthToken;

class AuthTokenManager extends StandardManager
{
    /** @var AuthTokenRepository  */
    protected $repository;

    public function __construct(AuthTokenRepository $repository, AuthToken $entity = null)
    {
        $this->repository = $repository;
        parent::__construct($repository, $entity);
    }

    /**
     * @param int $id
     * @return AuthToken
     */
    public function getEntityById($id)
    {
        return parent::getEntityById($id);
    }

    public function generateNewAuthToken()
    {
        do {
            $token = "";
            for ($i = 0; $i < 256; $i++) {
                $rand = rand(0, 61);
                if ($rand > 9) {
                    if ($rand > 35) {
                        $rand += ord('a') - 36;
                    } else {
                        $rand += ord('A') - 10;
                    }
                    $rand = chr($rand);
                }
                $token .= $rand;
            }
        } while($this->findOneByToken($token) != null);
        return $token;
    }

    /**
     * @param $token
     * @return null|AuthToken
     */
    public function findOneByToken($token)
    {
        return $this->findOneBy(["token" => $token]);
    }
}