var ListView = React.createClass({
  css: {
    narrow: {
      width: '85px'
    }
  },
  getInitialState: function() {
    return { Records: [] }
  },
  componentDidMount: function() {
    this.loadRecords(0, 25);
  },
  loadRecords: function(offset, limit) {
    $.ajax({
      url: '/api',
      data: {
        offset: offset,
        limit: limit,
        search: JSON.stringify(this.props.search)
      },
      success: function(data) {
        this.setState(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('/api', status, err.toString());
      }.bind(this)
    });
  },
  render: function() {
    return (
      <div>
        <h1>{this.props.title}</h1>
        <table className="records">
          <thead>
            <tr>
              <th style={this.css.narrow}>ID</th>
              <th>Märke</th>
              <th>Växellåda</th>
              <th>Serienummer</th>
              <th style={this.css.narrow}>Ändrad</th>
            </tr>
          </thead>
          <tbody>
            <tr className="spacer"><td></td></tr>
            {this.rows()}
          </tbody>
        </table>

        {this.pagination()}
      </div>
    );
  },
  rows: function() {
    return this.state.Records.map(function(record) {
      return (
        <tr onClick={this.recordClicked(record)}>
          <td style={{fontWeight: 'bold'}}>{record.Id}</td>
          <td>{record.Brand}</td>
          <td>{record.Transmission}</td>
          <td>{record.SerialNumber}</td>
          <td>{this.dateFor(record)}</td>
        </tr>
      );
    }.bind(this));
  },
  recordClicked: function(record) {
    return function() {
      this.props.onRecordClicked(record);
    }.bind(this);
  },
  pagination: function() {
    var atFirst = this.state.Offset > 0 ? '' : 'disabled'
    var atLast = this.state.Offset + this.state.Limit < this.state.Count ? '' : 'disabled';

    var first = <a href="javascript: void 0;" className={atFirst} onClick={this.firstClicked}>&raquo; Första</a>
    var prev = <a href="javascript: void 0;" className={atFirst} onClick={this.prevClicked}>&laquo; Föregående</a>
    var next = <a href="javascript: void 0;" className={atLast} onClick={this.nextClicked}>Nästa &raquo;</a>
    var last = <a href="javascript: void 0;" className={atLast} onClick={this.lastClicked}>Sista &raquo;</a>

    return (
      <div className="pagination">
        {first}
        {prev}
        {next}
        {last}
      </div>
    )
  },
  firstClicked: function() {
    this.loadRecords(0, 25);
  },
  prevClicked: function() {
    this.loadRecords(this.state.Offset - 25, 25)
  },
  nextClicked: function() {
    this.loadRecords(this.state.Offset + this.state.Limit, 25)
  },
  lastClicked: function() {
    this.loadRecords(Math.floor(this.state.Count / 25) * 25, 25)
  },
  dateFor: function(record) {
    var d = record.UpdatedAt.substr(0, 10);
    return (d[0] == '0') ? 'N/A' : d;
  }
});
