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}
            selectedItem={this.props.selectedItem}
            onItemClicked={this.props.onItemClicked}
            onItemMoved={this.props.onItemMoved}
            theme={this.props.theme} />
        </li>
      );
    }.bind(this));

    var appEntry = data.icon || data.label ?
      this.renderTreeItem(data):
      null
    ;

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

  },

  renderTreeItem: function(data) {
    return (
      <TreeItem data={data}
        selected={data.selected}
        {...this.props} />
    );
  }

});

var ProfileTree = React.createClass({

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

  render: function() {

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

  },

  renderTreeNode: function(data) {
    return (
      <TreeNode data={data}
        selectedItem={this.props.selectedItem}
        onItemClicked={this.onItemSelected}
        onItemMoved={this.onItemMoved}
        theme={this.props.theme} />
    );
  },

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

  onItemSelected: function(selectedItem) {
    this.props.dispatch(actions.edit.selectProfileItem(selectedItem));
  }

});

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

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