var React = require('react');
var Util = require('../util');
var DesktopAppItem = require('./desktop-app-item.jsx');
var IconThemeSelector = require('./icon-theme-selector.jsx');
var path = require('path');
var debug = require('debug')('pitaya:desktop-app-list');

module.exports = React.createClass({

  getInitialState: function() {
    return {
      desktopFiles: [],
      selectedTheme: null
    };
  },

  componentDidMount: function() {

    // Load system desktop apps
    var baseDirs = global.process.env.XDG_DATA_DIRS.split(':').map(function(baseDir){
      return path.join(baseDir, 'applications');
    });

    Util.DesktopApps.loadAllDesktopFiles('/usr/share/applications')
      .then(function(desktopFiles) {
        this.setState({ desktopFiles: desktopFiles });
      }.bind(this))
    ;
  },

  render: function() {

    var items = this.state.desktopFiles.map(function(desktopFile, i) {
      var desktopEntry = desktopFile.content['Desktop Entry'];
      return <DesktopAppItem theme={this.state.selectedTheme} key={desktopFile.path} desktopEntry={desktopEntry} />;
    }.bind(this));

    return (
      <div>
        <IconThemeSelector onThemeSelected={this.onThemeSelected} />
        <ul className="desktop-apps">
          {items}
        </ul>
      </div>
    );

  },

  onThemeSelected: function(theme) {
    console.log('Selected theme %s', theme);
    this.setState({ selectedTheme: theme });
  }

});
