export default {
  mounted() {
    let me = this; 
    let selectable = 1;
    if (this.el.dataset.selectable) {
      selectable = JSON.parse(this.el.dataset.selectable);
    }
    let table = new Tabulator(this.el, {
      columns: JSON.parse(this.el.dataset.columns),
      selectable: selectable,
      ajaxURL: "dummy_url",
      ajaxRequestFunc: (url, _config, params) => {
        return new Promise((resolve, _reject) => {
          this.pushEventTo(
            this.el,
            "fetch_data",
            params, 
            (reply, _ref) => {
              resolve(reply);
            }
          );
        });
      },
      filterMode: "remote",
      sortMode: "remote",
      pagination: true,
      paginationMode: "remote",
      selectablePersistence: true
    });
    
    table.on(
      "rowSelectionChanged",
      function (data, rows, selected, deselected) {
        
        if (selectable == true && selectable !== 1) {
          me.pushEventTo(
            me.el,
            "tabulator_rowselection_changed",
            data
          );
        }
      }
    );
    

    table.on("cellEditing", function(cell){
      console.log(cell)
      me.pushEventTo(me.el, "cellediting", cell.getData())
    })

    table.on("cellEdited", function(cell){
      console.log(cell)
      me.pushEventTo(me.el, "celledited", cell.getData())
    })

    table.on("rowSelected", function (row) {
      me.pushEventTo(me.el, "tabulator_rowselected", row.getData());
    });
    
    table.on("rowDeselected", function (row) {
      me.pushEventTo(me.el, "tabulator_rowdeselected", {});
    });
    
    table.on("dataProcessed", function () {
      let rows = this.rowManager.rows
      rows.forEach(row=>{
        if(row.data.selected != null){
          this.selectRow(row)
        } 
      })
    });
    
    this.handleEvent("update_tabulator", function (opts) {
      table.setData();
    });
  },
}
