var RecordView = React.createClass({
  getInitialState: function() {
    return { record: {} }
  },
  loadRecord: function(id) {
    this.setState({ record: {} });
    $.ajax({
      url: '/api/record/' + id,
      success: function(data) {
        this.setState({ record: data });
      }.bind(this),
      error: function(xhr, status, error) {
        console.error(xhr, status, error)
      }.bind(this)
    });
  },
  componentDidMount: function() {
    if (this.props.id == "new") {
      this.setState({ record: this.props.record || { Id: 0, Brand: 'Övriga', Cartype: 'Övriga', Text: '' }});
    } else {
      this.loadRecord(this.props.id);
    }
  },
  componentWillReceiveProps: function(props) {
    if (props.id == "new") {
      this.setState({ record: props.record || { Id: 0, Brand: 'Övriga', Cartype: 'Övriga', Text: '' }});
    } else {
      this.loadRecord(props.id);
    }
  },
  render: function() {
    if (this.props.id && this.state.record != null) {
      return (
        <div>
          {this.renderTitle()}
          <RecordForm record={this.state.record} text="true" onUpdate={this.onUpdate} />
          <button onClick={this.submit}>Spara</button>
          {this.renderCloneButton()}
        </div>
      )
    } else if (this.props.id && this.state.record == null) {
      return (
        <p>
          Den efterfrågade posten kunde inte hittas.
        </p>
      );
    }
  },
  renderTitle: function() {
    if (this.props.id == "new") {
      return <h1>Ny post</h1>
    } else {
      return <h1>UHR #{this.props.id}</h1>
    }
  },
  renderCloneButton: function() {
    if (this.props.showClone) {
      return <button onClick={this.clone} style={{ marginLeft: '20px' }}>Klona posten</button>
    }
  },
  onUpdate: function(record) {
    this.setState({ record: record });
  },
  submit: function() {
    $.ajax({
      url: '/api/record/',
      method: 'POST',
      data: JSON.stringify(this.state.record),
      contentType: 'application/json; charset: utf-8',
      success: function() {
        this.props.onSaved();
      }.bind(this)
    });
  },
  clone: function() {
    var clone = $.extend(true, {}, this.state.record);
    clone.Id = 0;

    this.props.showClone(clone);
  }
});
