<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'index' action of 'InicioController'.
 */
class LoginForm extends CFormModel{
	public $tipo_documento;
	public $documento;
	public $clave;
	public $token;

	private $_identity;

	/**
	 * 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('tipo_documento, documento, clave, token', 'required', 'message' => 'Este campo es requerido'),
			array(
				'documento',
				'match',
				'pattern' => '/^[0-9]+$/',
				'message' => 'Solo puede ingresar números del 0 al 9.'
			),
			array(
				'documento',
				'length',
				'min' => 9,
				'tooShort' => 'El RIF debe poseer 9 digitos.',
				'max' => 9,
				'tooLong' => 'El RIF debe poseer 9 digitos.'
			),
			// password needs to be authenticated
			array('clave', 'authenticate'),

			//Validar Tipo Documento
			array(
				'tipo_documento',
				'validarTipoDocumento'
			),
		);
	}

	// Validar que no ingrese otro tipo de documento
	public function validarTipoDocumento(){
		$tipo = $this->tipo_documento;

		if($tipo != ""){
			$tipos = array('J', 'G', 'V', 'E');

			if(!in_array($tipo, $tipos))
				$this->addError('tipo_documento', 'El Tipo de documento es incorrecto.');
		}else{
			$this->addError('tipo_documento', 'El Tipo de documento no puede estar vacío.');
		}
	}

	// Valida el número de documento
	public function validarDocumento(){
		$documento = $this->documento;

		if(strlen($documento) != 9)
			$this->addError("documento", "El RIF no es válido.");
	}


	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 * @param string $attribute the name of the attribute to be validated.
	 * @param array $params additional parameters passed with rule when being executed.
	 */
	public function authenticate($attribute,$params){
		if(!$this->hasErrors()){
			$this->_identity = new UserIdentity($this->documento,$this->clave, $this->tipo_documento, 1);
			/******************************
			1 = RIF equivocado
			2 = Contraseña erronea
			*******************************/
			if($this->_identity->authenticate() == 1 || $this->_identity->authenticate() == 2){
				$this->addError('clave','Usuario o clave incorrecta.');
			}

			// 99 = Usuario deshabilitado
			if($this->_identity->authenticate() == 99){
				$this->addError('clave', 'Usuario deshabilitado');
			}
		}
	}

	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login(){
		if($this->_identity===null){
			$this->_identity = new UserIdentity($this->documento,$this->clave, $this->tipo_documento, 1);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE){
			//$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
			Yii::app()->user->login($this->_identity);
			return true;
		}
		else
			return false;
	}

	// Nombre de los Label
	public function attributeLabels(){
		return array(
			'tipo_documento' => '',
			'documento' => 'RIF',
			'clave' => 'Clave',
			'token' => 'token',
		);
	}
}
