Ext.ns('ES');

ES.HeatingCounterEntriesGrid = Ext.extend(Ext.grid.GridPanel, {
  id: 'HeatingCounterEntriesPanel',
  autoload:false,
  enableHdMenu:false,
  width:442,
  store: new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url:'/process/extjs/site/consumption/heating/heatingcounterentries.php',
      method: 'POST'
    }),
    baseParams:{cmd: "list"},
    reader: new Ext.data.JsonReader({
      root: 'results',
      totalProperty: 'totalCount',
      id: 'id'
    },[
      {name: 'entry_id', type: 'int', mapping: 'uid'},
      {name: 'value', type: 'int', mapping: 'unit_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: 30
    });
    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,
        store: this.store,
        displayInfo: true
//        ,items:['->']
      }),
      cm: new Ext.grid.ColumnModel([
        {
          header: 'entry_id',
          dataIndex:'entry_id'
          ,hidden:true
          ,hideable:false
        },
        CheckColumn,
        {
          header: 'Valeur()',
          dataIndex: 'value',
          width: 90
        },{
          header: 'Prix(CHF)',
          dataIndex: 'price',
          width: 55
        },{
          header: 'Date de début',
          dataIndex: 'start_date',
          width: 80
        },{
          header: 'Date de fin',
          dataIndex: 'end_date',
          width: 70
        }
        ,this.action
      ])
    };
     // apply config
    Ext.apply(this, Ext.apply(this.initialConfig, config));
    // call parent initComponent
    ES.HeatingCounterEntriesGrid.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.HeatingCounterEntriesGrid.superclass.onRender.apply(this, arguments);
  } // eo function onRender
  ,refresh:function(counter_id) {
    this.show();
    this.counter_id = counter_id;
    this.setDateType();
    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.heatingCounterEntryFormWindow == null || !this.heatingCounterEntryFormWindow.isVisible()){
      this.heatingCounterEntryFormWindow = new ES.HeatingCounterEntryFormWindow();
      this.heatingCounterEntryForm = this.heatingCounterEntryFormWindow.items.itemAt(0);
      this.heatingCounterEntryFormButton = this.heatingCounterEntryForm.buttons[0];
      var scope_heatingcounterentry = this;
      this.heatingCounterEntryFormButton.on({
        scope:scope_heatingcounterentry,
        click:function(scope){
          this.addEntry();
        }
      });
      this.heatingCounterEntryFormWindow.show();
      this.heatingCounterEntryForm.setUnitLabel(this.unit);
      this.heatingCounterEntryForm.setDatetypeView(this.datetype);
    }else {
      this.heatingCounterEntryFormWindow.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){
    var cm = grid.colModel;
    var readindex = cm.findColumnIndex('entry_id');
    var record = grid.getStore().getAt(rowIndex);
    this.entry_id = record.get('entry_id');
    if(this.heatingCounterEntryFormWindow == null || !this.heatingCounterEntryFormWindow.isVisible()){
      this.heatingCounterEntryFormWindow = new ES.HeatingCounterEntryFormWindow();
      this.heatingCounterEntryFormWindow.title = "Modification de la consommation de chauffage";
      this.heatingCounterEntryForm = this.heatingCounterEntryFormWindow.items.itemAt(0);
      this.heatingCounterEntryFormButton = this.heatingCounterEntryForm.buttons[0];
      var scope_heatingcounterentry = this;
      this.heatingCounterEntryFormButton.on({
        scope:scope_heatingcounterentry,
        click:function(scope){
          this.editEntry();
        }
      });
      
      this.heatingCounterEntryFormWindow.show();
      this.heatingCounterEntryForm.setUnitLabel(this.unit);
      this.heatingCounterEntryForm.setDatetypeView(this.datetype);
    }else {
      this.heatingCounterEntryFormWindow.toFront();
    }
    this.heatingCounterEntryForm.setField('value',record.get('value'));
    this.heatingCounterEntryForm.setField('price',record.get('price'));
    this.heatingCounterEntryForm.setField('startdate',record.get('start_date'));
    this.heatingCounterEntryForm.setField('enddate',record.get('end_date'));
  }
  ,editEntry:function(){
    if(this.datetype == 'simple'){
      this.editEntrySimpleDate();
    }else{
      this.editEntryDoubleDate();
    }
  }
  ,addEntry: function() {
    if(this.heatingCounterEntryForm.isValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/heating/heatingcounterentries.php',
        params: {
          cmd:"add",
          counter_id:this.counter_id,
          value: this.heatingCounterEntryForm.getField('value').getValue(),
          price: this.heatingCounterEntryForm.getField('price').getValue(),
          startdate: this.heatingCounterEntryForm.getField('startdate').getValue().format("Ymd"),
          enddate: this.heatingCounterEntryForm.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 de chauffage'
//              ,'La consommation chauffage a été insérée.'
//              ,function(){
                scope.ownerCt.refresh(scope.ownerCt.counter_id);
                scope.ownerCt.heatingCounterEntryFormWindow.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');
    }
  }
  ,editEntryDoubleDate: function() {
    if(this.heatingCounterEntryForm.isValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/heating/heatingcounterentries.php',
        params: {
          cmd:"update",
          entry_id:this.entry_id,
          value: this.heatingCounterEntryForm.getField('value').getValue(),
          price: this.heatingCounterEntryForm.getField('price').getValue(),
          startdate: this.heatingCounterEntryForm.getField('startdate').getValue().format("Ymd"),
          enddate: this.heatingCounterEntryForm.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 de chauffage'
                ,'La consommation de chauffage a été modifiée.'
                ,function(){
                  scope.ownerCt.refresh(scope.ownerCt.counter_id);
                  scope.ownerCt.heatingCounterEntryFormWindow.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');
    }
  }
  ,editEntrySimpleDate: function() {
    if(this.heatingCounterEntryForm.isValid()){
      Ext.Ajax.request({
        ownerCt: this,
        waitMsg: 'Please wait...',
        url: '/process/extjs/site/consumption/heating/heatingcounterentries.php',
        params: {
          cmd:"update",
          entry_id:this.entry_id,
          value: this.heatingCounterEntryForm.getField('value').getValue(),
          price: this.heatingCounterEntryForm.getField('price').getValue(),
          enddate: this.heatingCounterEntryForm.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 de chauffage'
                ,'La consommation de chauffage a été modifiée.'
                ,function(){
                  scope.ownerCt.refresh(scope.ownerCt.counter_id);
                  scope.ownerCt.heatingCounterEntryFormWindow.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/heating/heatingcounterentries.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
      });
    }
  }
  ,setDateType: function(){
    var cm=this.colModel;
    Ext.Ajax.request({
      ownerCt: this,
      waitMsg: 'Please wait...',
      url: '/process/extjs/site/consumption/heating/heatingcounterentries.php',
        params: {
          cmd:"datetype",
          counter_id:this.counter_id
        }
      ,success: function(response,scope){
        var result = Ext.util.JSON.decode(response.responseText);
        switch(result.success){
          case 1:
            scope.ownerCt.datetype = result.data.datetype;
            scope.ownerCt.labelunit=result.data.unit;
            scope.ownerCt.energy=result.data.energy;
              if(scope.ownerCt.datetype=="simple"){
                cm.setHidden(4, true);
                cm.setColumnHeader(5,"Date");
              }else{
                cm.setHidden(4, false);
                cm.setColumnHeader(5,"Date de fin");
              }
          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');
      }
    })
  }
  ,setUnitLabel: function(unit){
    this.unit=unit;
    this.cm=this.colModel;
    if(unit=="m3"){
      this.cm.setColumnHeader(2,"Valeur(KWh)")
    }else{
      this.cm.setColumnHeader(2,"Valeur("+unit+")");
    }
  }
  ,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;
  }
  ,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();
  }
  ,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('ESheatingcounterentriesgrid', ES.HeatingCounterEntriesGrid);


