Ext.ns('ES');

ES.ElectricityCounterEntriesGrid = Ext.extend(Ext.grid.GridPanel, {
  id: 'ElectricityCounterEntriesPanel',
  autoload:false,
  enableHdMenu:false,
  height:400,
  width:442,
  store: new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url:'/process/extjs/site/consumption/electricity/electricitycounterentries.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: 'valuehc', type: 'int', mapping: 'valuehc'},
      {name: 'price', type: 'int', mapping: 'price'},
      {name: 'start_date', type: 'string', mapping: 'start_date'},
      {name: 'end_date', type: 'string', mapping: 'end_date'}
    ])
  }),
  //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'
      }]
      ,callbacks:{
        'icon-edit':function(grid, record, action, row, col) {
          this.initEditElectricityCounterEntryFormWindow2(grid, record, action, row, col);
        }.createDelegate(this)
      }
    });
    var CheckColumn = new Ext.grid.CheckColumn({
      header: " ",
      dataIndex: 'checkbox',
      hideable:false,
      width: 20
    });
    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: 'Supression',
          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',
          id:'entry_id'
          ,hidden:true
          ,hideable:false
        },
        CheckColumn,
        {
          header: 'Valeur HP(KWh)',
          dataIndex: 'value',
          id:'value',
          tooltip: 'Valeur heures pleines',
          width: 82
        },{
          header: 'Valeur HC(KWh)',
          dataIndex: 'valuehc',
          id:'valuehc',
          tooltip: 'Valeur heures creuses',
          width: 83
        },{
          header: 'Prix(CHF)',
          dataIndex: 'price',
          id:'price',
          tooltip: 'prix',
          width: 50
        },{
          header: 'Date début',
          dataIndex: 'start_date',
          id:'start_date',
          width: 65
        },{
          header: 'Date de fin',
          dataIndex: 'end_date',
          id:'end_date',
          width: 65
        }
        ,this.action
      ])
    }; 
     // apply config
    Ext.apply(this, Ext.apply(this.initialConfig, config));
    // call parent initComponent
    ES.ElectricityCounterEntriesGrid.superclass.initComponent.call(this);
    //this.on('rowdblclick',this.initEditElectricityCounterEntryFormWindow1,this);
    this.topToolbar.items.itemAt(0).on('click',this.initAddElectricityCounterEntryFormWindow,this);
    this.topToolbar.items.itemAt(1).on('click',this.deleteEntries,this);
  } // end of function initComponent
  ,onRender:function() {
    ES.ElectricityCounterEntriesGrid.superclass.onRender.apply(this, arguments);
  } // eo function onRender
  ,refresh:function(counter_id) {
    this.show();
    this.counter_id = counter_id;
    this.setFairType();
    this.store.load({
      url:this.url
      ,waitMsg:'Loading...'
      ,params:{cmd:'list',counter_id:counter_id,start:0,limit:10}
    });
  }
  ,initAddElectricityCounterEntryFormWindow:function (grid, record, action, row, col){
    if(this.electricityCounterEntryFormWindow == null || !this.electricityCounterEntryFormWindow.isVisible()){
      this.electricityCounterEntryFormWindow = new ES.ElectricityCounterEntry_FormWindow();
      this.electricityCounterEntryForm = this.electricityCounterEntryFormWindow.items.itemAt(0);
      this.electricityCounterEntryFormButton = this.electricityCounterEntryForm.buttons[0];
      var scope_electricityCounterEntry = this;
      this.electricityCounterEntryFormButton.on({
        scope:scope_electricityCounterEntry,
        click:function(scope){
          this.addElectricityCounterEntry();
        }
      });
      this.electricityCounterEntryFormWindow.show();
      this.electricityCounterEntryForm.setFairtypeView(this.fairtype);
    } else {
      this.electricityCounterEntryFormWindow.toFront();
    }
  }
  ,initEditElectricityCounterEntryFormWindow1:function (grid,rowIndex,e){
    this.initEditElectricityCounterEntryFormWindow(grid,rowIndex);
  }
  ,initEditElectricityCounterEntryFormWindow2:function (grid, record, action, rowIndex, col){
    this.initEditElectricityCounterEntryFormWindow(grid,rowIndex);
  }
  ,initEditElectricityCounterEntryFormWindow: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.electricityCounterEntryFormWindow == null || !this.electricityCounterEntryFormWindow.isVisible()){
      this.electricityCounterEntryFormWindow = new ES.ElectricityCounterEntry_FormWindow();
      this.electricityCounterEntryFormWindow.title = "Modification de la consommation d'electricité";
      this.electricityCounterEntryForm = this.electricityCounterEntryFormWindow.items.itemAt(0);
      this.electricityCounterEntryFormButton = this.electricityCounterEntryForm.buttons[0];
      var scope_electricityCounterEntry = this;
      this.electricityCounterEntryFormButton.on({
        scope:scope_electricityCounterEntry,
        click:function(scope){
          this.editElectricityCounterEntry();
        }
      });
      this.electricityCounterEntryFormWindow.show();
      this.electricityCounterEntryForm.setFairtypeView(this.fairtype);
    }else {
      this.electricityCounterEntryFormWindow.toFront();
    }
    this.electricityCounterEntryForm.setField('value',record.get('value'));
    this.electricityCounterEntryForm.setField('valuehc',record.get('valuehc'));
    this.electricityCounterEntryForm.setField('price',record.get('price'));
    this.electricityCounterEntryForm.setField('startdate',record.get('start_date'));
    this.electricityCounterEntryForm.setField('enddate',record.get('end_date'));
  }
  ,addElectricityCounterEntry: function() {
    if(this.electricityCounterEntryForm.isValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/electricity/electricitycounterentries.php',
        params: {
          cmd:"add",
          counter_id:this.counter_id,
          value: this.electricityCounterEntryForm.getField('value').getValue(),
          valueHC: this.electricityCounterEntryForm.getField('valuehc').getValue(),
          price: this.electricityCounterEntryForm.getField('price').getValue(),
          startdate: this.electricityCounterEntryForm.getField('startdate').getValue().format("Ymd"),
          enddate: this.electricityCounterEntryForm.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 electricité'
//                ,'La consommation electricité a été insérée.'
//                ,function(){
                  scope.ownerCt.refresh(scope.ownerCt.counter_id);
                  scope.ownerCt.electricityCounterEntryFormWindow.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');
    }
  },setFairType: function(){
    var cm=this.colModel;
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/electricity/electricitycounterentries.php',
        params:{
          cmd:"fairtype",
          counter_id:this.counter_id
        }
        ,success: function(response,scope){
          var result = Ext.util.JSON.decode(response.responseText);
          switch(result.success){
            case 1:
              scope.ownerCt.fairtype = result.data.fairtype;
              if(scope.ownerCt.fairtype=="simple"){
                cm.setHidden(3, true);
                cm.setColumnHeader(2,"Value (KWh)");
              }else{
                cm.setHidden(3, false);
                cm.setColumnHeader(2,"Valeur HP(KWh)");
              }
            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');
        }
      })
  },editElectricityCounterEntry: function() {
    if(this.electricityCounterEntryForm.isValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/electricity/electricitycounterentries.php',
        params: {
          cmd:"update",
          entry_id:this.entry_id,
          value: this.electricityCounterEntryForm.getField('value').getValue(),
          valueHC:this.electricityCounterEntryForm.getField('valuehc').getValue(),
          price: this.electricityCounterEntryForm.getField('price').getValue(),
          startdate: this.electricityCounterEntryForm.getField('startdate').getValue().format("Ymd"),
          enddate: this.electricityCounterEntryForm.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 electricitè'
                ,'La consommation d electricitè a été modifiée.'
                ,function(){
                  scope.ownerCt.refresh(scope.ownerCt.counter_id);
                  scope.ownerCt.electricityCounterEntryFormWindow.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/electricity/electricitycounterentries.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
      });
    }
  }
  ,demoModality: function() {
    var cm= this.colModel;
    cm.setHidden(1, true);
    cm.setHidden(7, 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')){
        wcounters.push(this.getStore().getAt(i).get('entry_id'));
      }
    }
    return wcounters;
  }
  ,countCheck:function() {
    var check = 0;
    for(i = 0; i< this.getStore().getCount(); i++){
      if(this.getStore().getAt(i).get('checkbox')){
        check++;
      }
    }
    return check;
  }
});

Ext.reg('ESelectricitycounterentriesgrid', ES.ElectricityCounterEntriesGrid);

