var React = require('react');
var connect = require('react-redux').connect;
var actions = require('../../store/actions');
var TreeItem = require('./tree-item.jsx');

var TreeNode = React.createClass({

  render: function() {

    var data = this.props.data || {};
    var subItems = data.items || [];

    var listElements = subItems.map(function(subItem, i) {
      return (
        <li key={i} >
          <TreeNode data={subItem} onItemMoved={this.props.onItemMoved} />
        </li>
      );
    }.bind(this));

    var appEntry = data.icon || data.label ?
      <TreeItem data={data} onItemMoved={this.props.onItemMoved} /> :
      null
    ;

    return (
      <div className="tree-item">
        {appEntry}
        <ul>
          {listElements}
        </ul>
      </div>
    );

  }

});

var ProfileTree = React.createClass({

  componentDidMount: function() {
    this.props.dispatch(actions.launcher.loadProfile('./default-profile.json'));
  },

  render: function() {

    return (
      <div className="profile-tree">
        <TreeNode data={this.props.profile} onItemMoved={this.onItemMoved} />
      </div>
    );

  },

  onItemMoved: function(movedItem, targetItem) {
    this.props.dispatch(actions.edit.moveProfileItem(movedItem, targetItem));
  }

});

function select(state) {
  return {
    profile: state.profile
  };
}

module.exports = connect(select)(ProfileTree);
