<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class FormularioLoginUsuario extends CFormModel {

    public $username;
    public $password;
    public $recuerdame;

    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
    public function rules() {
        return array(
            array('username, password', 'required'),
            array('recuerdame', 'boolean'),
            array('password', 'authenticate'),
        );
    }

    /**
     * Declares attribute labels.
     */
    public function attributeLabels() {
        return array(
            'recuerdame' => UsuarioModule::t("Recordarme más tarde"),
            'username' => UsuarioModule::t("Nombre de usuario o email"),
            'password' => UsuarioModule::t("Contraseña"),
        );
    }

    /**
     * Authenticates the password.
     * This is the 'authenticate' validator as declared in rules().
     */
    public function authenticate($attribute, $params) {
        if (!$this->hasErrors()) {  // we only want to authenticate when no input errors
            $identity = new UserIdentity($this->username, $this->password);
            $identity->authenticate();
            switch ($identity->errorCode) {
                case UserIdentity::ERROR_NONE:
                    $duration = $this->recuerdame ? Yii::app()->controller->module->rememberMeTime : 0;
                    Yii::app()->user->login($identity, $duration);
                    break;
                case UserIdentity::ERROR_EMAIL_NOVALIDO:
                    $this->addError("username", UsuarioModule::t("Email is incorrect."));
                    break;
                case UserIdentity::ERROR_USERNAME_INVALID:
                    $this->addError("username", UsuarioModule::t("Username is incorrect."));
                    break;
                case UserIdentity::ERROR_ESTADO_NOACTIVO:
                    $this->addError("estado", UsuarioModule::t("You account is not activated."));
                    break;
                case UserIdentity::ERROR_ESTADO_BLOQUEADO:
                    $this->addError("estado", UsuarioModule::t("You account is blocked."));
                    break;
                case UserIdentity::ERROR_PASSWORD_INVALID:
                    $this->addError("password", UsuarioModule::t("Password is incorrect."));
                    break;
            }
        }
    }

}
