/** @jsx React.DOM */

var FeatureBox = React.createClass({

  getInitialState: function() {
    return {features: []};
  },

  componentWillMount: function() {
    this.refresh();
  },

  refresh: function() {
    this.props.featureRepo.fetchFeatures(function(featureData){
      this.setState({features: featureData});
    }.bind(this));
  },

  handleNewFeature: function() {
    this.newFeature();
    return false;
  },

  newFeature: function() {
    this.refs.featureEditModal.show({}, this.createFeature);
  },

  createFeature: function(feature) {
    this.props.featureRepo.createFeature(feature, this.refresh);
  },

  editFeature: function(feature) {
    this.refs.featureEditModal.show(feature, this.updateFeature);
  },

  updateFeature: function(feature) {
    console.log("updating", feature);
  },

  render: function() {
    return (
      <div className="featureBox">
        <h2>Features</h2>
        <button type="button" className="btn btn-primary" onClick={this.handleNewFeature}>New Feature</button>
        <FeatureForm ref="featureEditModal"/>
        <FeatureList features={this.state.features} editFeature={this.editFeature} />
      </div>
    );
  }
});

var FeatureList = React.createClass({
  render: function() {
    var self = this;
    var featureNodes = this.props.features.map(function (feature, index) {
      return (
        <Feature key={index} feature={feature} editFeature={this.props.editFeature}/>
      )
    }.bind(this));
    return (
      <div className="featureList">{featureNodes}</div>
    );
  }
});

var Feature = React.createClass({
  switchState: function(){
    switch(this.props.feature.master_switch_state) {
      case true:
        return "Override on";
      case false:
        return "Override off";
      case null:
        return "Dynamic";
    }
  },

  handleEdit: function(){
    this.props.editFeature(this.props.feature);
    false;
  },

  render: function() {
    var feature = this.props.feature;

    return(
      <div className="feature panel panel-primary">
        <div className="featureTitle panel-heading">
          <h3 className="panel-title">{feature.title}</h3>
        </div>
        <div className="panel-body row">
          <div className="featureDescription col-md-9"> {feature.description} </div>
          <div className="featureMasterSwitchState col-md-1"> {this.switchState()}</div>
          <div className="editFeature col-md-1"> <a href="#" onClick={this.handleEdit}>edit</a></div> <div className="deleteFeature col-md-1">delete</div>
        </div>
      </div>
    )
  }
});

var FeatureForm = React.createClass({
  getInitialState: function() {
    return {editingFeature: {}, dirty: false}
  },

  componentDidMount: function() {
    var self = this;
    var domNode = $(this.getDOMNode());
    domNode.on("hide.bs.modal", function(e) {
      if (this.state.dirty) {
        return false;
      }
    }.bind(this));
  },

  show: function(feature, onSave) {
    var editingFeature = $.extend({}, feature);
    this.setState({editingFeature: editingFeature, onSave: onSave, dirty: true})
    $(this.getDOMNode()).modal({keyboard: false});
  },

  handleChange: function() {
    var feature = this.state.editingFeature;
    feature.title = this.refs.title.getDOMNode().value;
    feature.description = this.refs.description.getDOMNode().value;
    feature.master_switch_state = this.refs.master_switch_state.getDOMNode().value;
    feature.definition = null;
    this.setState({editingFeature: feature, dirty: true});
  },

  modalTitle: function() {
    if (this.state.editingFeature === {}) {
      return "Add Feature";
    } else {
      return "Edit Feature";
    }
  },

  handleSaveFeature: function() {
    var feature = this.state.editingFeature;
    this.state.onSave(feature);
    this.replaceState({editingFeature: {}, dirty: false}, function(){
      $(this.getDOMNode()).modal('hide');
    }.bind(this));
    false;
  },

  handleCancel: function() {
    this.replaceState({editingFeature: {}, dirty: false}, function(){
      $(this.getDOMNode()).modal('hide');
    }.bind(this));
    false;
  },

  render: function() {
    var feature = this.state.editingFeature;
    return (
      <div className="featureEdit modal fade">
        <div className="modal-dialog modal-lg">
          <div className="modal-content">
            <div className="modal-header">
              <h3 className="modal-title">{this.modalTitle()}</h3>
            </div>
            <div className="modal-body">
              <form className="featureEditForm" ref="form" role="form">
                <div className="form-group">
                  <label>Feature title</label>
                  <input id="featureTitleInput" className="form-control" type="text" ref="title" value={feature.title} onChange={this.handleChange}/>
                </div>
                <div className="form-group">
                  <label for="featureDescriptionInput">Feature title</label>
                  <textarea id="featureDescriptionInput" className="form-control" type="text" ref="description" value={feature.description} onChange={this.handleChange}/>
                </div>
                <div className="form-group">
                  <label for="featureMasterSwitchStateInput">Master Switch</label>
                  <select id="featureMasterSwitchStateInput" value={feature.master_switch_state} className="form-control" ref="master_switch_state" onChange={this.handleChange}>
                    <option value="dynamic">Dynamic</option>
                    <option value="on">On</option>
                    <option value="off">Off</option>
                  </select>
                </div>
              </form>
            </div>
            <div className="modal-footer">
              <button type="button" className="btn" onClick={this.handleCancel}>Cancel</button>
              <button type="button" className="btn btn-primary" onClick={this.handleSaveFeature}>Save</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
});

var FeatureRepo = function(url){
  this.url = url;
};

FeatureRepo.prototype.fetchFeatures = function(onSuccess, onError){
  $.ajax({
    url: this.url,
    dataType: 'json',
    success: onSuccess,
    error: onError || function(xhr, status, err) {
      console.log(status, err);
    }
  });
};

FeatureRepo.prototype.createFeature = function(feature, onSuccess, onError){
  $.ajax({
    url: this.url,
    contentType: 'application/json',
    type: 'POST',
    data: JSON.stringify(feature),
    success: onSuccess,
    error: onError || function(xhr, status, err) {
      console.log(status, err);
    }
  });
}

var featureRepo = new FeatureRepo("/admin/api/features");
React.renderComponent(
  <FeatureBox featureRepo={featureRepo}/>,
  document.getElementById("iodized")
);


@@ -906,16 +906,50 @@
 es%3C/h2%3E%0A
+        %3Cdiv className=%22panel%22%3E%0A  
         
@@ -1064,45 +1064,48 @@
    %3C
-FeatureForm ref=%22featureEditModa
+/div%3E%0A        %3Cdiv className=%22pane
 l%22
-/
 %3E%0A
+  
     
@@ -1186,16 +1186,77 @@
 ure%7D /%3E%0A
+        %3C/div%3E%0A        %3CFeatureForm ref=%22featureEditModal%22/%3E%0A
       %3C/

tweak layout