<?php

/**
 * This is the model class for table "configuracion.conf_varibale_banco".
 *
 * The followings are the available columns in table 'configuracion.conf_varibale_banco':
 * @property integer $id
 * @property string $nombre_variable
 * @property string $descripcion_variable
 * @property string $nomenclatura_variable
 * @property string $condicion_variable
 */
class ConfVaribaleBanco extends CActiveRecord
{
	public $longitud, $relleno, $posicion_inicio, $posicion_fin, $relleno_direccion, $separador_miles, $separador_decimal, $formato_fecha;
    public $inicia;
    public $actual;
    public $operacion;

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'configuracion.conf_varibale_banco';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('nombre_variable, descripcion_variable, nomenclatura_variable', 'required','on'=>'registrar_variable'),
			array('longitud, posicion_inicio, posicion_fin', 'numerical', 'integerOnly'=>true, 'on'=>'formato_variable'),

			array('longitud, posicion_inicio, posicion_fin', 'length', 'max'=>3,'on'=>'formato_variable'),
			array('formato_fecha, posicion_fin', 'length', 'max'=>8,'on'=>'formato_variable'),
			array('relleno, separador_decimal, separador_miles', 'length', 'max'=>1,'on'=>'formato_variable'),
			 array('nomenclatura_variable,', 'filter', 'filter'=>'trim','on'=>'formato_variable'),
			// array('formato_fecha', 'validarFormatoFecha','on'=>'formato_variable'),

			array('nomenclatura_variable', 'unico','on'=>'registrar_variable'),
			array('nomenclatura_variable', 'formato','on'=>'registrar_variable'),
			array('nombre_variable, descripcion_variable, nomenclatura_variable, condicion_variable, relleno_direccion, inicia, actual, operacion, extra', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, nombre_variable, descripcion_variable, nomenclatura_variable, condicion_variable', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'idBancoVariable' => array(self::HAS_MANY, 'BancoVariable', 'id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'nombre_variable' => 'Nombre de la variable',
			'descripcion_variable' => 'Descripción de la variable',
			'nomenclatura_variable' => 'nomencaltura de la variable',
			'condicion_variable' => 'Condición de la variable',
			'relleno_direccion' => 'Completar hacia la    ',
			'relleno' => 'Caracter de relleno',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('nombre_variable',$this->nombre_variable,true);
		$criteria->compare('descripcion_variable',$this->descripcion_variable,true);
		$criteria->compare('nomenclatura_variable',$this->nomenclatura_variable,true);
		$criteria->compare('condicion_variable',$this->condicion_variable,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public function unico(){
		// @todo Please modify the following code to remove attributes that should not be searched.
		if(!$this->hasErrors('nomenclatura_variable')){
			$model = ConfVaribaleBanco::model()->find('UPPER(nomenclatura_variable)=:nomenclatura_variable',
					array(':nomenclatura_variable'=>strtoupper($this->nomenclatura_variable)));
			if($model){
				if($this->isNewRecord){
					$this->addError('nomenclatura_variable', 'Nomenclatura de Variable repetido');
				}
				else{
					if($model->id !=$this->id)
						$this->addError('nomenclatura_variable', 'Nomenclatura de Variable repetido');
				}
			}
		}
	}
	
	public function formato(){
		// @todo Please modify the following code to remove attributes that should not be searched.
		if(!$this->hasErrors('nomenclatura_variable')){
			if(!preg_match('/\[\{([a-z]|_|[0-9])*\}\]/',$this->nomenclatura_variable)){
				$this->addError('nomenclatura_variable', 'Error en el formato de la Nomenclatura');
			}
		}
	}

	public function afterFind()
    {
        if ($this->extra !== null) {
            $extra = json_decode($this->extra);
            $this->inicia = $extra->inicia;
            $this->actual = $extra->actual;
            $this->operacion = $extra->operacion;
        }
    }

    public function isReference()
    {
        if ($this->isNewRecord) {
            return false;
        }

        return $this->nomenclatura_variable === '[{referencia}]';
    }

    public function setExtra($attributes= [])
    {
        $this->extra = json_encode($attributes);
    }

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return ConfVaribaleBanco the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    public static function actualizarExtraActual($referencia)
    {
        $model = self::model()->findByPk($referencia['id']);

        if ($model->extra === null) {
            return;
        }

        return $model->saveAttributes([
            'extra' => json_encode([
                'inicia' => intval($model->inicia),
                'actual' => intval($referencia['valor']),
                'operacion' => boolval($model->operacion),
            ]),
        ]);
    }
}
