var React = require('react');
var minimist = require('minimist');
var gui = global.window.require('nw.gui');
var Util = require('./util');
var CategoryHeader = require('./components/category-header.jsx');
var AppList = require('./components/app-list.jsx');
var AnimateMixin = require('./mixins/animate');

// Internal constants
var DEFAULT_PROFILE = './default-profile.json';
var PROCESS_OPTS = minimist(gui.App.argv);

var App = React.createClass({

  mixins: [AnimateMixin],

  getInitialState: function() {
    return {
      currentItemPath: '',
      currentItem: null
    };
  },

  componentDidMount: function() {
    Util.System.loadJSONFile(PROCESS_OPTS.profile || DEFAULT_PROFILE)
      .then(function(profile) {
        this.setState({ profile: profile, currentItem: profile, currentItemPath: '' });
      }.bind(this))
    ;
  },

  render: function() {

    var currentItem = this.state.currentItem;
    var items = currentItem ? currentItem.items : [];
    var currentItemPath = this.state.currentItemPath;

    var header = currentItemPath !== '' ?
      ( <CategoryHeader
          onBackClick={this.onBackClick}
          item={currentItem}
          itemPath={currentItemPath} /> ) :
      null
    ;

    return (
      <div className="launcher">
        {header}
        <AppList ref="appList" items={items} parentPath={currentItemPath} onItemClick={this.onItemClick} />
      </div>
    );

  },

  onBackClick: function(itemPath) {

    var parentPath = this._normalizeItemPath(itemPath).slice(0, -1);
    var parentItem = this._getItemByPath(parentPath);

    this.play(this.refs.appList, 'slide-out-right 250ms ease-in-out')
      .then(function() {
        this.setState({currentItem: parentItem, currentItemPath: parentPath.join('.')});
        return this.play(this.refs.appList, 'slide-in-left 250ms ease-in-out');
      }.bind(this))
    ;

  },

  onItemClick: function(evt, itemPath, item) {

    if(item.exec) {

      console.info('Launching application "'+item.exec+'"...');
      evt.currentTarget.classList.add('pulse');

      Util.System.runApp(item.exec)
        .then(function() {
          evt.currentTarget.classList.remove('pulse');
        })
        .catch(function(err) {
          evt.currentTarget.classList.remove('pulse');
        })
      ;

    } else {
      this.play(this.refs.appList, 'slide-out-left 250ms ease-in-out')
        .then(function() {
          this.setState({ currentItemPath: itemPath, currentItem: item });
          return this.play(this.refs.appList, 'slide-in-right 250ms ease-in-out');
        }.bind(this))
      ;
    }

  },

  _getItemByPath: function(itemPath, rootItem) {

    rootItem = rootItem || this.state.profile;
    itemPath = this._normalizeItemPath(itemPath);

    var itemIndex = itemPath[0];

    if(itemIndex === undefined) {
      return rootItem;
    }

    if(!('items' in rootItem)) {
      return undefined;
    }

    var subItem = rootItem.items[itemIndex];

    if(itemPath.length === 0) {
      return subItem;
    }

    return this._getItemByPath(itemPath.slice(1), subItem);

  },

  _normalizeItemPath: function(itemPath) {

    if( Array.isArray(itemPath) ) return itemPath;

    if((typeof itemPath === 'string' && itemPath.length === 0) || !itemPath) return [];

    return itemPath.split('.').reduce(function(arr, index) {
      if(index !== '') {
        arr.push(+index);
      }
      return arr;
    }, []);

  }

});

var rootEl = document.getElementById('pitaya');
React.render(<App />, rootEl);
