<?php

namespace Login\Authentication\Adapter;

use Application\Model\Status;
use Application\Model\Utenti;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Authentication\Result;
use Zend\Crypt\Password\Bcrypt;

/**
 * Class EliminaCode
 * @package Login\Authentication\Adapter
 */
class EliminaCode implements AdapterInterface
{
    /**
     * @var \Zend\Crypt\Password\Bcrypt
     */
    protected $_bcrypt;

    /**
     * @var
     */
    protected $_username;

    /**
     * @var
     */
    protected $_password;

    /**
     * @var
     */
    protected $_utentiModel;

    /**
     * @param Utenti $utentiModel
     */
    public function __construct(Utenti $utentiModel)
    {
        $this->_bcrypt = new Bcrypt();
        $this->setUtentiModel($utentiModel);
    }

    /**
     * @return Result
     */
    public function authenticate()
    {
        if (empty($this->_username) || empty($this->_password)) {
            return new Result(Result::FAILURE, null);
        }

        $hashPassword = $this->getUtentiModel()->findEqual(array(
            'username' => $this->_username,
            'status' => Status::STATUS_ATTIVO
        ));

        $code = $this->_bcrypt->verify($this->_password, $hashPassword['password']) ? Result::SUCCESS : Result::FAILURE;

        /**
         * GetRuoloUser
         *
         * Aggiungo all'array $hashPassword,
         * il ruolo dell'utente loggato e la rotta per il redirect.
         */
        if ($code === Result::SUCCESS) {

            $ruolo = $this->getUtentiModel()->getRuolo($hashPassword['id']);
            $hashPassword['ruolo'] = $ruolo['ruolo'];
        }

        return new Result($code, $hashPassword);
    }

    /**
     * @param $username
     */
    public function setUsername($username)
    {
        $this->_username = $username;
    }

    /**
     * @param $password
     */
    public function setPassword($password)
    {
        $this->_password = $password;
    }


    /**
     * @param mixed $utentiModel
     */
    public function setUtentiModel($utentiModel)
    {
        $this->_utentiModel = $utentiModel;
    }

    /**
     * @return mixed
     */
    public function getUtentiModel()
    {
        return $this->_utentiModel;
    }
}
