Ext.ns('ES');

ES.WaterCounterGrid = Ext.extend(Ext.grid.GridPanel, {
  id: 'WaterCounterPanel',
  autoload:true,
  enableHdMenu:false,
  store: new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url:'/process/extjs/site/consumption/water/watercounter.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"}
  }),
  initComponent:function() {
    this.actionEdit = new Ext.ux.grid.RowActions({
      header:'Modifier'
      ,width: 45
      ,scope:this
      ,autoWidth:false
      ,hideMode:'display'
      ,keepSelection:true
      ,actions:[{
        iconCls:'icon-edit'
        ,qtip:'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.actionEdit,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'
          })
        ]
      }),
      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.actionEdit,
        this.actionDetails
      ])
    };
     // apply config
    Ext.apply(this, Ext.apply(this.initialConfig, config));
    // call parent initComponent
    ES.WaterCounterGrid.superclass.initComponent.call(this);
    this.topToolbar.items.itemAt(0).on('click',this.initAddFormWindow,this);
  } // end of function initComponent
  ,onRender:function() {
    ES.WaterCounterGrid.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.waterCounterFormWindow == null || !this.waterCounterFormWindow.isVisible()){
      this.waterCounterFormWindow = new ES.waterCounterFormWindow();
      this.waterCounterForm = this.waterCounterFormWindow.items.itemAt(0);
      this.waterCounterFormButton = this.waterCounterForm.buttons[0];
      var scope_watercounter = this;
      this.waterCounterFormButton.on({
         scope:scope_watercounter,
         click:function(scope){
           this.addCounter();
         }
      });
      this.waterCounterFormWindow.show();
    } else {
      this.waterCounterFormWindow.toFront();
    }
  }
  ,addCounter: function() {
    if(this.waterCounterForm.isValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/water/watercounter.php',
        params: {
          cmd:"add",
          countername: this.waterCounterForm.getField('watercountername').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 eau'
//                ,'Le compteur eau a été créé.'
//                ,function(){
                  scope.ownerCt.refresh(0);
                  scope.ownerCt.waterCounterFormWindow.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');
    }
  }
  ,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;
  }
  ,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;
  }
  ,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;
  }
  ,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();
   }
});

Ext.reg('ESwatercountergrid', ES.WaterCounterGrid);

