import Ember from 'ember';
import _ from 'lodash/lodash';

const {
  computed,
  observer
} = Ember;

const {
  sort,
  alias,
  bool
} = computed;

const { keys } = Object;

/**
  Sortable Filterable Table Component

  @class SortFilterTable
  @extends Ember.Component
*/
export default Ember.Component.extend({
  hasBlock: bool('template').readOnly(),

  /**
   Config: Signal if filter input field should be included

   @property filterable
   @returns Bool
   @public
  */
  filterable: true,

  /**
    Map raw data in to Ember A and Ember Objects

    @property _rows
    @returns Array
    @private
  */
  _rows: computed('table.rows', function() {
    let rows = this.get('table.rows');
    return Ember.A(rows.map((row) => {
      return Ember.Object.create(row);
    }));
  }),

  /**
    Array of properties to determine sort order

    @property _sortOrder
    @returns Array
    @private
  */
  _sortOrder: Ember.A([]),

  /**
    Rows sorted by specified sort order

    @property sortedRows
    @returns Array
    @public
  */
  sortedRows: sort('_rows', '_sortOrder'),

  /**
   Extract column headers from keys

   @property headers
   @returns Array
   @public
  */
  headers: computed('sortedRows', function() {
    return Ember.A(keys(this.get('sortedRows.firstObject')));
  }),

  /**
    Store separator for headers

    @property _separator
    @returns String
    @private
  */
  _separator: null,

  /**
    Replaces hyphens or underscores with spaces (used to prettify headers)

    @method _handleSeparators
    @private
  */
  _handleSeparators(str) {
    if ((/-/).test(str)) {
      //hyphen
      this.set('_separator', '-');
      return str.replace(/-/, ' ');
    } else if ((/_/).test(str)) {
      //underscore
      this.set('_separator', '_');
      return str.replace(/_/g, ' ');
    } else if ((/ /).test(str)) {
      //space
      this.set('_separator', ' ');
      return str;
    } else {
      return str;
    }
  },

  /**
    Assemble pretty labels from column headers/keys

    @property labels
    @returns Array
    @public

  */
  labels: computed('headers', function() {
    let headers = this.get('headers');
    return Ember.A(headers.map((item) => {
      return Ember.Object.create({
        _key: item,
        name: this._handleSeparators(item),
        sort: 'null'
      });
    }));
  }),

  /**
    Signal wether current sort param is asc or desc

    @property _ascending
    @type Bool
    @private
  */
  _ascending: true,

  /**
    Calculated total number of columns (colspan)

    @property totalColumns
    @returns Number
    @public
  */
  totalColumns: alias('labels.length'),

  /**
    Filter by search param from input

    @method _applyFilter
    @private
  */
  _applyFilter: observer('filter', function() {
    let rows = this.get('sortedRows');

    //case insensitive
    let filterQuery = (this.get('filter')).toLowerCase();

    rows.filter((row) => {
      let values = _.values(row);
      let filterExp = new RegExp(filterQuery);
      return row.set('_filtered', !(filterExp).test((values.join(',')).toLowerCase()));
    });

  }),

  actions: {
    /**
      Toggle sort by property asc/desc

      @method sortBy
    */
    sortBy(label) {
      let header = label.get('name').replace(/ /g, this.get('_separator'));
      let labels = this.get('labels');

      this.toggleProperty('_ascending');
      let direction = this.get('_ascending') ? 'asc' : 'desc';

      labels.setEach('sort', null);
      label.set('sort', direction);

      this.set('_sortOrder', [ header + ':' + direction ]);
    },

    /**
      Send values up to actions

      @method sendEditAction
    */
    sendEditAction(row, key, value, action) {
      if (this.get(action)) {
        this.sendAction(action, {
          'row' : row,
          'key' : key,
          'value' : value
        });
        row.toggleProperty('_editingRow');
      }
    },

    /**
      Display input field for editing

      @method
    */
    editValue(row, key) {
      let rows = this.get('_rows');
      rows.setEach('_editingRow', null);
      row.set('_editingRow', key);
    },
  }
});

@@ -1582,169 +1582,85 @@
     
-if ((/-/).test(str)) %7B%0A      //hyphen%0A      this.set('_separator', '-');%0A      return str.replace(/-/, ' ');%0A    %7D else if ((/_/).test(str)) %7B%0A      //underscore
+let separator = str.match(/%5B-  _%5D/);%0A    if (separator && separator.length) %7B
 %0A   
@@ -1689,11 +1689,20 @@
 r', 
-'_'
+separator%5B0%5D
 );%0A 
@@ -1729,85 +1729,19 @@
 ace(
-/_/g, ' ');%0A    %7D else if ((/ /).test(str)) %7B%0A      //space%0A      this.set('_
+new RegExp(
 sepa
@@ -1749,17 +1749,20 @@
 ator
-'
+%5B0%5D)
 , ' ');%0A
     
@@ -1757,34 +1757,16 @@
 , ' ');%0A
-      return str;%0A
     %7D el

simplify _handleSeparators method for scalability