import Ember from 'ember';
import layout from '../templates/components/data-table';

export default Ember.Component.extend({
  layout,
  isLoadingData: true,
  store: Ember.inject.service(),
  columns: [],
  columnNames: [],
  showRows: 5,
  page: 1,
  showActions: true,

  didInsertElement() {
    if(this.get('columns.length') !== this.get('columnNames.length')) {
      console.warn('DATA-TABLE: A quantidade de parâmetros de "column" e "columnNames" é diferente e pode gerar erros de visualisação');
    }
    this.resetQueryParams();
    this.loadData();
  },

  loadData() {
    this.set('isLoadingData', true);
    this.get('store')
      .query(this.get('modelName'), this.get('filters'))
      .then((model) => {
        this.set('model', model);
        this.set('isLoadingData', false);
      });
  },

  resetQueryParams() {
    this.set('page', 1);
    this.set('filters', {
      limit: this.get('showRows'),
      skip: 0
    });
  },

  fakeRowsCounter: Ember.computed('showRows', function() {
    let counter = [];

    for (let i = 1; i <= this.get('showRows'); i++) {
      counter.push(i);
    }

    return counter;
  }),

  buildQuery(search) {
    var query = { or: [] };
    this.get('columns').map(function (column) {
      var obj = {};
      obj[column] = {contains: search};
      query.or.push(obj);
    });
    console.log(query);
    return query;
  },

	actions: {
		changePage(page) {
      this.set('page', page);
			this.set('filters.skip', (page-1) * this.get("showRows"));;
			this.loadData();
		},
    searchOnKeyUp: function(searchTerms) {
      this.resetQueryParams();

			if (searchTerms === '') {
				this.loadData();
			} else {
				clearTimeout(this.get('searchDelay'));
				this.set('searchDelay', setTimeout(() => {
					this.set('filters.where', JSON.stringify(this.buildQuery(searchTerms)));
					this.loadData();
				}, 300));
			}
		}
	}
});

@@ -285,24 +285,268 @@
 Element() %7B%0A
+    if(typeof this.get('columnNames') === 'string' ) %7B%0A      this.set('columnNames', this.get('columnNames').split(','));%0A    %7D%0A    if(typeof this.get('columns') === 'string' ) %7B%0A      this.set('columns', this.get('columns').split(','));%0A    %7D%0A
     if(this.
@@ -1579,32 +1579,8 @@
 %7D);%0A
-    console.log(query);%0A
     
@@ -2099,16 +2099,175 @@
 %09%09%09%7D%0A%09%09%7D
+,%0A    delete(model) %7B%0A      var answer = confirm(%22Tem certeza que deseja excluir o registro?%22);%0A      if(answer) %7B%0A        model.destroyRecord();%0A      %7D%0A    %7D
 %0A%09%7D%0A%7D);%0A

implementa controle de colunas pelo componente