Ext.ns('ES');

ES.HeatingCounterGrid = Ext.extend(Ext.grid.GridPanel, {
  id: 'HeatingCounterPanel',
  autoload:true,
  enableHdMenu:false,
  store: new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url:'/process/extjs/site/consumption/heating/heatingcounter.php',
      method: 'POST'
    }),
    reader: new Ext.data.JsonReader({
      root: 'results',
      totalProperty: 'totalCount',
      id: 'id'
    },[
      {name: 'counter_id', type: 'int', mapping: 'uid'},
      {name: 'countername', type: 'string', mapping: 'name'}
    ]),
    sortInfo:{field: 'countername', direction: "ASC"}
  }),
  initComponent:function() {
    this.action = new Ext.ux.grid.RowActions({
      header:'Modifier'
      ,width: 50
      ,scope:this
      ,autoWidth:false
      ,hideMode:'display'
      ,keepSelection:true
      ,actions:[{
        iconCls:'icon-edit'
        ,tooltip:'Modifier'
      }]
    });
    this.actionDetails = new Ext.ux.grid.RowActions({
      header:'Données'
      ,width: 50
      ,scope:this
      ,autoWidth:false
      ,hideMode:'display'
      ,keepSelection:true
      ,actions:[{
        iconCls:'icon-management'
        ,qtip:'Gestion'
      }]
    });
    var CheckColumn = new Ext.grid.CheckColumn({
      header: "&nbsp;",
      dataIndex: 'checkbox',
      hideable:false,
      width: 25
    });
    var config = {
      plugins:[CheckColumn,this.action,this.actionDetails],
      tbar: new Ext.Toolbar({
        items:[new Ext.Toolbar.Button({
          text: 'Ajout d\'un compteur'
          ,iconCls:'add'
        }),
        new Ext.Toolbar.Button({
          text: 'Suppression',
          iconCls:'remove',
          autowidth:true
        })]}),
        cm: new Ext.grid.ColumnModel([
        {
          header: 'counter_id',
          dataIndex:'counter_id'
          ,hidden:true
          ,hideable:false
        },
        CheckColumn,
        {
          header: 'Nom du compteur',
          dataIndex: 'countername',
          width: 120,
          hideable:false
        }, this.action,
        this.actionDetails
      ])
    };
     // apply config
    Ext.apply(this, Ext.apply(this.initialConfig, config));
    // call parent initComponent
    ES.HeatingCounterGrid.superclass.initComponent.call(this);
    this.topToolbar.items.itemAt(0).on('click',this.initAddFormWindow,this);
  } // end of function initComponent
  ,onRender:function() {
    ES.HeatingCounterGrid.superclass.onRender.apply(this, arguments);
    this.refresh('tn_id_isset');
  } // eo function onRender
  ,refresh:function() {
    this.store.load({
      url:this.url
      ,waitMsg:'Loading...'
      ,params:{cmd:'list'}    //
    });
  }
  ,initAddFormWindow:function (){
    if(this.heatingCounterFormWindow == null || !this.heatingCounterFormWindow.isVisible()){
      this.heatingCounterFormWindow = new ES.HeatingCounterFormWindow();
      this.heatingCounterForm = this.heatingCounterFormWindow.items.itemAt(0);
      this.heatingEnergyCombo=this.heatingCounterFormWindow.items.itemAt(0).items.itemAt(0).items.itemAt(2);
      this.heatingUnitCombo=this.heatingCounterFormWindow.items.itemAt(0).items.itemAt(0).items.itemAt(3);
      this.heatingCounterFormButton = this.heatingCounterForm.buttons[0];
      var scope_heatingcounter = this;
      this.heatingCounterFormButton.on({
        scope:scope_heatingcounter,
        click:function(scope){
          this.addCounter();
        }
      });
      this.heatingCounterFormWindow.show();
      this.heatingCounterForm.setLabel('simpleRadio','');
      this.heatingCounterForm.setLabel('doubleRadio','');
    }else {
      this.heatingCounterFormWindow.toFront();
    }
  }
  ,addCounter: function() {
    if(this.heatingCounterForm.isValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/heating/heatingcounter.php',
        params: {
          cmd:"add"
          ,countername: this.heatingCounterForm.getField('heatingcountername').getValue()
          ,unit_uid:this.heatingUnitCombo.getValue()
          ,energy_uid: this.heatingEnergyCombo.getValue()
          ,filling_type:this.heatingCounterForm.getField('consumptionType').getValue()
        },
        success: function(response,scope){
          var result = Ext.util.JSON.decode(response.responseText);
          switch(result.success){
            case 1:
//              Ext.MessageBox.alert(
//                'Création du compteur chauffage'
//                ,'Le compteur chauffage a été créé.'
//                ,function(){
                  scope.ownerCt.refresh(0);
                  scope.ownerCt.heatingCounterFormWindow.close();
//                }
//              ,scope);
            break;
            default:
              Ext.MessageBox.alert('Attention',result.error);
              break;z
          }
        },
        failure: function(response) {
          Ext.MessageBox.alert('error','L application n a pas pu se connecter a la base de données. Veuillez réessayer plus tard');
        }
      });
    } else {
      Ext.MessageBox.alert('Attention','Le formulaire n est pas valide');
    }
  }
  ,getCheckBoxValues:function() {
    var hcounters = [];
    for(i = 0; i< this.getStore().getCount(); i++){
      if(this.getStore().getAt(i).get('checkbox')){//if the checkbox is selected
        hcounters.push(this.getStore().getAt(i).get('counter_id'));
      }
    }
    return hcounters;
  }
  ,isCheck:function(counter_id) {
    var isCheck = false;
    for(i = 0; i< this.getStore().getCount(); i++){
      if(this.getStore().getAt(i).get('checkbox')){//if the checkbox is selected
        if(this.getStore().getAt(i).get('counter_id') == counter_id){
          isCheck = true;
        }
      }
    }
    return isCheck;
  }
  ,demoModality: function() {
    var cm= this.colModel;
    cm.setHidden(1, true);
    cm.setHidden(3, true);
    this.topToolbar.items.itemAt(0).disable();
    this.topToolbar.items.itemAt(1).disable();
   }
  ,countCheck:function() {
    var check = 0;
    for(i = 0; i< this.getStore().getCount(); i++){
      if(this.getStore().getAt(i).get('checkbox')){//if the checkbox is selected
        check++;
      }
    }
    return check;
  }
});

Ext.reg('ESheatingcountergrid', ES.HeatingCounterGrid);

