<?php

/**
 * UsuarioIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

    private $_id;

    // Constantes de error declaradas en la clase padre
    //const ERROR_NONE=0;
    //const ERROR_USERNAME_INVALID=1;
    //const ERROR_PASSWORD_INVALID=2;
    //const ERROR_UNKNOWN_IDENTITY=100;

    const ERROR_EMAIL_NOVALIDO = 3;
    const ERROR_ESTADO_NOACTIVO = 4;
    const ERROR_ESTADO_BLOQUEADO = 5;

    /**
     * Authenticates a user.
     * The example implementation makes sure if the username and password
     * are both 'demo'.
     * In practical applications, this should be changed to authenticate
     * against some persistent user identity storage (e.g. database).
     * @return boolean whether authentication succeeds.
     */
    public function authenticate() {
        if (strpos($this->username, "@")) {
            $usuario = Usuario::model()->notsafe()->findByAttributes(array('email' => $this->username));
        } else {
            $usuario = Usuario::model()->notsafe()->findByAttributes(array('username' => $this->username));
        }
        if ($usuario === null)
            if (strpos($this->username, "@")) {
                $this->errorCode = self::ERROR_EMAIL_NOVALIDO;
            } else {
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            } else if (Yii::app()->getModule('usuario')->cifrar($this->password) !== $usuario->password)
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        else if ($usuario->estado == 0 && Yii::app()->getModule('usuario')->loginNotActiv == false)
            $this->errorCode = self::ERROR_ESTADO_NOACTIVO;
        else if ($usuario->estado == -1)
            $this->errorCode = self::ERROR_ESTADO_BLOQUEADO;
        else {
            $this->_id = $usuario->id;
            $this->username = $usuario->username;
            $this->errorCode = self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    /**
     * @return integer the ID of the user record
     */
    public function getId() {
        return $this->_id;
    }

}