Ext.ns('ES');

ES.WaterCounterEntriesGrid = Ext.extend(Ext.grid.GridPanel, {
  id: 'WaterCounterEntriesPanel',
  autoload:false,
  enableHdMenu:false,
  width:442,
  store: new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url:'/process/extjs/site/consumption/water/watercounterentries.php',
      method: 'POST'
    }),
    baseParams:{cmd: "list"},
    reader: new Ext.data.JsonReader({
      root: 'results',
      totalProperty: 'totalCount',
      id: 'id'
    },[
      {name: 'entry_id', type: 'int', mapping: 'entry_id'},
      {name: 'value', type: 'int', mapping: 'value'},
      {name: 'price', type: 'int', mapping: 'price'},
      {name: 'start_date', type: 'string', mapping: 'start_date'},
      {name: 'end_date', type: 'string', mapping: 'end_date'}
    ])
  }),
  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'
      }]
      ,callbacks:{
        'icon-edit':function(grid, record, action, row, col) {
          this.initEditFormWindow2(grid, record, action, row, col);
        }.createDelegate(this)
      }
    });
    var CheckColumn = new Ext.grid.CheckColumn({
      header: " ",
      dataIndex: 'checkbox',
      hideable:false,
      width: 35
    });
    var config = {
      plugins:[CheckColumn,this.action],
      tbar: new Ext.Toolbar({
        items:[new Ext.Toolbar.Button({
          text: 'Ajout d\'entrée'
          ,iconCls:'add'
      }),
        new Ext.Toolbar.Button({
          text: 'Suppression',
          iconCls:'remove'
      })]}),
      bbar: new Ext.PagingToolbar({
        pageSize: 10,
        ownerCt: this,
        store: this.store,
        displayInfo: true,
        items:['->']
      }),
      cm: new Ext.grid.ColumnModel([
        {
          header: 'entry_id',
          dataIndex:'entry_id'
          ,hidden:true
          ,hideable:false
        },
        CheckColumn,
        {
          header: 'Valeur(m3)',
          dataIndex: 'value',
          width: 78
        },{
          header: 'Prix(CHF)',
          dataIndex: 'price',
          width: 78
        },{
          header: 'Date de début',
          dataIndex: 'start_date',
          width: 85
        },{
          header: 'Date de fin',
          dataIndex: 'end_date',
          width: 85
        }
        ,this.action
        ])
    }; 
     // apply config
    Ext.apply(this, Ext.apply(this.initialConfig, config));
    // call parent initComponent
    ES.WaterCounterEntriesGrid.superclass.initComponent.call(this);
//    this.on('rowdblclick',this.initEditFormWindow1,this);
    this.topToolbar.items.itemAt(0).on('click',this.initAddFormWindow,this);
    this.topToolbar.items.itemAt(1).on('click',this.deleteEntries,this);
  } // end of function initComponent
  ,onRender:function() {
    ES.WaterCounterEntriesGrid.superclass.onRender.apply(this, arguments);
  } // eo function onRender
  ,refresh:function(counter_id) {
    this.show();
    this.counter_id = counter_id;
    this.store.load({
       url:this.url
      ,waitMsg:'Loading...'
      ,params:{cmd:'list',counter_id:counter_id,start:0,limit:10}
    });
  }
  ,initAddFormWindow:function (grid, record, action, row, col){
    if(this.waterCounterEntryFormWindow == null || !this.waterCounterEntryFormWindow.isVisible()){
      this.waterCounterEntryFormWindow = new ES.waterCounterEntryFormWindow();
      this.waterCounterEntryForm = this.waterCounterEntryFormWindow.items.itemAt(0);
      this.waterCounterEntryFormButton = this.waterCounterEntryForm.buttons[0];
      var scope_watercounterentry = this;
      this.waterCounterEntryFormButton.on({
         scope:scope_watercounterentry,
         click:function(scope){
           this.addEntry();
         }
      });
      this.waterCounterEntryFormWindow.show();
    } else {
      this.waterCounterEntryFormWindow.toFront();
    }
  }
  ,initEditFormWindow1:function (grid,rowIndex,e){
    this.initEditFormWindow(grid,rowIndex);
  }
  ,initEditFormWindow2:function (grid, record, action, rowIndex, col){
    this.initEditFormWindow(grid,rowIndex);
  }
  ,initEditFormWindow:function (grid, rowIndex){
    cm = grid.colModel;
    readindex = cm.findColumnIndex('entry_id');
    var record = grid.getStore().getAt(rowIndex);
    this.entry_id = record.get('entry_id');
    if(this.waterCounterEntryFormWindow == null || !this.waterCounterEntryFormWindow.isVisible()){
      this.waterCounterEntryFormWindow = new ES.waterCounterEntryFormWindow();
      this.waterCounterEntryFormWindow.title = "Modification de la consommation d'eau";
      this.waterCounterEntryForm = this.waterCounterEntryFormWindow.items.itemAt(0);
      this.waterCounterEntryFormButton = this.waterCounterEntryForm.buttons[0];
      var scope_watercounterentry = this;
      this.waterCounterEntryFormButton.on({
         scope:scope_watercounterentry,
         click:function(scope){
           this.editEntry();
         }
      });
      this.waterCounterEntryFormWindow.show();
    } else {
      this.waterCounterEntryFormWindow.toFront();
    }
    this.waterCounterEntryForm.setField('value',record.get('value'));
    this.waterCounterEntryForm.setField('price',record.get('price'));
    this.waterCounterEntryForm.setField('startdate',record.get('start_date'));
    this.waterCounterEntryForm.setField('enddate',record.get('end_date'));
  }
  ,addEntry: function() {
    if(this.waterCounterEntryForm.isValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/water/watercounterentries.php',
        params: {
          cmd:"add",
          counter_id:this.counter_id,
          value: this.waterCounterEntryForm.getField('value').getValue(),
          price: this.waterCounterEntryForm.getField('price').getValue(),
          startdate: this.waterCounterEntryForm.getField('startdate').getValue().format("Ymd"),
          enddate: this.waterCounterEntryForm.getField('enddate').getValue().format("Ymd")
        },
        success: function(response,scope){
          var result = Ext.util.JSON.decode(response.responseText);
          switch(result.success){
          case 1:
//            Ext.MessageBox.alert(
//              'Saisie de données d eau'
//              ,'La consommation eau a été insérée.'
//              ,function(){
                scope.ownerCt.refresh(scope.ownerCt.counter_id);
                scope.ownerCt.waterCounterEntryFormWindow.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');
    }
  }
  ,editEntry: function() {
    if(this.waterCounterEntryForm.isValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/water/watercounterentries.php',
        params: {
          cmd:"update",
          entry_id:this.entry_id,
          value: this.waterCounterEntryForm.getField('value').getValue(),
          price: this.waterCounterEntryForm.getField('price').getValue(),
          startdate: this.waterCounterEntryForm.getField('startdate').getValue().format("Ymd"),
          enddate: this.waterCounterEntryForm.getField('enddate').getValue().format("Ymd")
        },
        success: function(response,scope){
          var result = Ext.util.JSON.decode(response.responseText);
          switch(result.success){
          case 1:
            Ext.MessageBox.alert(
              'Modification de données d eau'
              ,'La consommation d eau a été modifiée.'
              ,function(){
                scope.ownerCt.refresh(scope.ownerCt.counter_id);
                scope.ownerCt.waterCounterEntryFormWindow.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');
    }
  }
  ,deleteEntries: function() {
    if(this.countCheck() > 0) {
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/water/watercounterentries.php',
        params: {
          entry_ids:Ext.util.JSON.encode(this.getCheckBoxValues())
          ,cmd:'delete'
        },
        success: function(response,scope){
          scope.ownerCt.refresh(scope.ownerCt.counter_id);
        },
        failure: function() {
        }
      });
    } else {
      Ext.MessageBox.show({
        title: 'Aucun élément sélectionné',
        msg: 'Pour supprimer, veuillez sélectionner les éléments à supprimer avec les checkbox',
        width: 300
      });
    }
  }
  ,getCheckBoxValues:function() {
    var wentries = [];
    for(i = 0; i< this.getStore().getCount(); i++){
      if(this.getStore().getAt(i).get('checkbox')){
        wentries.push(this.getStore().getAt(i).get('entry_id'));
      }
    }
    return wentries;
  }
  ,countCheck:function() {
    var check = 0;
    for(i = 0; i< this.getStore().getCount(); i++){
      if(this.getStore().getAt(i).get('checkbox')){
        check++;
      }
    }
    return check;
  }
  ,demoModality: function() {
    var cm= this.colModel;
    cm.setHidden(1, true);
    cm.setHidden(6, true);
    this.topToolbar.items.itemAt(0).disable();
    this.topToolbar.items.itemAt(1).disable();
   }
});

Ext.reg('ESwatercounterentriesgrid', ES.WaterCounterEntriesGrid);

