import React, {PropTypes} from 'react';
import _ from 'lodash';
import {Link} from 'react-router';

const AlertsTable = React.createClass({
  propTypes: {
    alerts: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.string,
      time: PropTypes.string,
      value: PropTypes.string,
      host: PropTypes.string,
      level: PropTypes.string,
    })),
    source: PropTypes.shape({
      id: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
    }).isRequired,
  },

  getInitialState() {
    return {
      searchTerm: '',
      filteredAlerts: this.props.alerts,
      sortDirection: null,
      sortKey: null,
    };
  },

  componentWillReceiveProps(newProps) {
    this.filterAlerts(newProps.alerts, this.state.searchTerm);
  },

  filterAlerts(allAlerts, searchTerm) {
    const alerts = allAlerts.filter((h) => {
      return h.name.toLowerCase().search(searchTerm.toLowerCase()) !== -1 ||
              h.host.toLowerCase().search(searchTerm.toLowerCase()) !== -1 ||
              h.level.toLowerCase().search(searchTerm.toLowerCase()) !== -1;
    });
    this.setState({searchTerm, filteredAlerts: alerts});
  },

  changeSort(key) {
    // if we're using the key, reverse order; otherwise, set it with ascending
    if (this.state.sortKey === key) {
      const reverseDirection = (this.state.sortDirection === 'asc' ? 'desc' : 'asc');
      this.setState({sortDirection: reverseDirection});
    } else {
      this.setState({sortKey: key, sortDirection: 'asc'});
    }
  },

  sort(alerts, key, direction) {
    switch (direction) {
      case 'asc':
        return _.sortBy(alerts, (e) => e[key]);
      case 'desc':
        return _.sortBy(alerts, (e) => e[key]).reverse();
      default:
        return alerts;
    }
  },

  render() {
    const {id} = this.props.source;
    const alerts = this.sort(this.state.filteredAlerts, this.state.sortKey, this.state.sortDirection);
    return (
      <div className="panel panel-minimal">
        <div className="panel-heading u-flex u-ai-center u-jc-space-between">
          <h2 className="panel-title">{this.props.alerts.length} Alerts</h2>
          <SearchBar onSearch={_.wrap(this.props.alerts, this.filterAlerts)} />
        </div>
        <div className="panel-body">
          <table className="table v-center">
            <thead>
              <tr>
                <th onClick={() => this.changeSort('name')} className="sortable-header">Name</th>
                <th onClick={() => this.changeSort('level')} className="sortable-header">Level</th>
                <th onClick={() => this.changeSort('time')} className="sortable-header">Time</th>
                <th onClick={() => this.changeSort('host')} className="sortable-header">Host</th>
                <th onClick={() => this.changeSort('value')} className="sortable-header">Value</th>
              </tr>
            </thead>
            <tbody>
              {
                alerts.map(({name, time, value, host, level}) => {
                  return (
                    <tr key={`${name}-${time}-${host}-${value}`}>
                      <td className="monotype">{name}</td>
                      <td className={`monotype alert-level-${level.toLowerCase()}`}>{level}</td>
                      <td className="monotype">{(new Date(Number(time)).toISOString())}</td>
                      <td className="monotype">
                        <Link to={`/sources/${id}/hosts/${host}`}>
                          {host}
                        </Link>
                      </td>
                      <td className="monotype">{value}</td>
                    </tr>
                  );
                })
              }
            </tbody>
          </table>
        </div>
      </div>
    );
  },
});

const SearchBar = React.createClass({
  propTypes: {
    onSearch: PropTypes.func.isRequired,
  },

  handleChange() {
    this.props.onSearch(this.refs.searchInput.value);
  },

  render() {
    return (
      <div className="users__search-widget input-group">
        <input
          type="text"
          className="form-control"
          placeholder="Filter Alerts by Name..."
          ref="searchInput"
          onChange={this.handleChange}
        />
        <div className="input-group-addon">
          <span className="icon search" aria-hidden="true"></span>
        </div>
      </div>
    );
  },
});

export default AlertsTable;

@@ -779,19 +779,8 @@
 rts(
-allAlerts, 
 sear
@@ -803,42 +803,157 @@
 nst 
-alerts = allAlerts.filter((h) =%3E %7B
+filteredAlerts = this.props.alerts.filter((h) =%3E %7B%0A      if (h.host === null %7C%7C h.name === null %7C%7C h.level === null) %7B%0A        return false;%0A      %7D%0A
 %0A   
@@ -982,32 +982,33 @@
 erCase().search(
+(
 searchTerm.toLow
@@ -993,32 +993,33 @@
 arch((searchTerm
+)
 .toLowerCase()) 
@@ -1062,32 +1062,33 @@
 erCase().search(
+(
 searchTerm.toLow
@@ -1073,32 +1073,33 @@
 arch((searchTerm
+)
 .toLowerCase()) 
@@ -1151,16 +1151,17 @@
 .search(
+(
 searchTe
@@ -1162,16 +1162,17 @@
 archTerm
+)
 .toLower
@@ -1244,16 +1244,8 @@
 erts
-: alerts
 %7D);%0A
@@ -2263,34 +2263,8 @@
 ch=%7B
-_.wrap(this.props.alerts, 
 this
@@ -2276,17 +2276,16 @@
 erAlerts
-)
 %7D /%3E%0A   
@@ -3947,16 +3947,17 @@
 eChange(
+e
 ) %7B%0A    
@@ -3980,28 +3980,15 @@
 rch(
-this.refs.searchInpu
+e.targe
 t.va
@@ -4207,36 +4207,8 @@
 ..%22%0A
-          ref=%22searchInput%22%0A
     

Fix filtering in alerts table