// App component : represents the whole app.

App = React.createClass({

  // This mixin makes the getMeteorData work.
  mixins: [ReactMeteorData],

  // Loads items from the Tasks collection and puts them on this.data.tasks.
  getMeteorData() {
    let result = {
      tasks: Tasks.find({}).fetch()
    };
    // Meteor._debug("result", result);
    return result;
  },

  renderTasks() {
    return this.data.tasks.map((task) => {
      // Meteor._debug(task._id);
      return <Task key={task._id} task={task} />;
    });
  },

  handleSubmit(event) {
    event.preventDefault();
    // Meteor._debug('refs', this.refs);

    // Find the text field via the React ref.
    var text = ReactDOM.findDOMNode(this.refs.textInput).value.trim();

    Tasks.insert({
      text: text,
      createdAt: new Date() // Current time
    });

    // Clear form to allow a new input.
    ReactDOM.findDOMNode(this.refs.textInput).value = '';
  },

  render() {
    return (
      <div className="container">
        <header>
          <h1>Todo list</h1>

          {/* These are JSX comments. */}
          {/* Beware: for React, onsubmit is not the same as onSubmit, the former doesn't work */}
          <form className="new-task" onSubmit={this.handleSubmit} >
            <input type="text" ref="textInput" placeholder="Type to add new tasks" />
            </form>
          </header>

        <ul>
          {this.renderTasks()}
        </ul>
      </div>
    );
  }
});
