var Table = React.createClass({
  // TODO: Declare all propTypes
  propTypes: {
    title: React.PropTypes.string,
    id: React.PropTypes.number,
    url: React.PropTypes.string
  },

  getInitialState: function() {
    return {
      data: null,
      id: "",
      title: ""
    };
  },

  loadTableFromServer: function() {
    $.getJSON(this.props.url, function(result) {
      if (this.isMounted()) {
        this.setState({ data: result });
      }
    }.bind(this));
  },


  componentDidMount: function() {
    this.loadTableFromServer();
  },

  handleSeatSubmit: function(seat_id, action) {
    $.ajax({
      url: window.location.pathname + '/seats/' + seat_id + '/' + action,
      type: 'PATCH',
      dataType: 'json',
      success: function (data, textStatus, jqXHR) {
        // success callback
        this.loadTableFromServer();
      }.bind(this),
      error: function (jqXHR, textStatus, errorThrown) {
        // error callback
      }
    });
  },

  render: function() {
    if (!this.state.data) {
      return <div>Loading...</div>;
    }
    return (
      <div className="table" id={"table-" + this.state.data.id}>
        <h1>{this.state.data.title}</h1>
        <Game id={this.state.data.current_game_id} current_user={this.state.data.current_user} onSeatSubmit={this.handleSeatSubmit} />
      </div>
    );
  }
});
