Ext.ns('ES');

ES.ElectricityCounterGrid = Ext.extend(Ext.grid.GridPanel, {
  id: 'electricityCounterPanel',
  autoload:true,
  enableHdMenu:false,
  store: new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url:'/process/extjs/site/consumption/electricity/electricitycounter.php',
      method: 'POST'
    }),
    reader: new Ext.data.JsonReader({
      root: 'results',
      totalProperty: 'totalCount',
      id: 'id'
    },[
      {name: 'counter_id', type: 'int', mapping: 'counter_id'},
      {name: 'countername', type: 'string', mapping: 'countername'}
    ]),
    sortInfo:{field: 'countername', direction: "ASC"}
  }),
  enableColLock:false,
  //clicksToEdit:1,
  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.ElectricityCounterGrid.superclass.initComponent.call(this);
    this.topToolbar.items.itemAt(0).on('click',this.initAddElectricityCounterFormWindow,this);
    //this.topToolbar.items.itemAt(1).on('click',this.deleteCounters,this);
  } // end of function initComponent
  ,onRender:function() {  
    ES.ElectricityCounterGrid.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'}
    });
  }
  ,initAddElectricityCounterFormWindow:function (){
    if(this.electricityCounterFormWindow == null || !this.electricityCounterFormWindow.isVisible()){
      this.electricityCounterFormWindow = new ES.ElectricityCounter_FormWindow();
      this.electricityCounterForm = this.electricityCounterFormWindow.items.itemAt(0);
      this.electricityCounterFormButton = this.electricityCounterForm.buttons[0];
      var scope_electricitycounter = this;
      this.electricityCounterFormButton.on({
        scope:scope_electricitycounter,
        click:function(scope){
          this.addElectricityCounter();
        }
      });
      this.electricityCounterFormWindow.show();
    }else {
      this.electricityCounterFormWindow.toFront();
    }
  }
  ,addElectricityCounter: function() {
    if(this.electricityCounterForm.isValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/electricity/electricitycounter.php',
        params: {
          cmd:"add",
          countername: this.electricityCounterForm.getField('electricitycountername').getValue(),
          fairtype: this.electricityCounterForm.getField('fairtype').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 electricité'
//                ,'Le compteur electricité a été créé.'
//                ,function(){
                  scope.ownerCt.refresh(0);
                  scope.ownerCt.electricityCounterFormWindow.close();
//                }
//              ,scope);
            break;
            default:
              Ext.MessageBox.alert('Attention',result.error);
            break;
          }
        },
        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');
    }
  }
  ,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();
  }
  ,getCheckBoxValues:function() {
    var wcounters = [];
    for(i = 0; i< this.getStore().getCount(); i++){
      if(this.getStore().getAt(i).get('checkbox')){//if the checkbox is selected
        wcounters.push(this.getStore().getAt(i).get('counter_id'));
      }
    }
    return wcounters;
  }
  ,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;
  }
  ,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;
  }
  ,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;
  }
});

Ext.reg('ESelectricitycountergrid', ES.ElectricityCounterGrid);

