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

var ProfileMenu = React.createClass({

    render: function() {

      return (
        <div className="profile-menu">
          <input ref="fileInput" style={{display: 'none'}} filter=".json" type="file" />
          <button className="btn btn-default" onClick={this.handleOpenClick}>Ouvrir</button>
          <button className="btn btn-primary" onClick={this.handleSaveClick}>Enregistrer</button>
        </div>
      );

    },

    handleOpenClick: function() {
      var dispatch = this.props.dispatch;
      this.showFileDialog()
        .then(function(profilePath) {
          dispatch(actions.common.loadProfile(profilePath));
        })
      ;
    },

    handleSaveClick: function() {

      var dispatch = this.props.dispatch;
      var profile = this.props.profile;
      var profilePath = this.props.profilePath;

      var promise = profilePath ? Promise.resolve(profilePath) : this.showFileDialog(true);

      promise.then(function(profilePath) {
        dispatch(actions.edit.saveProfile(profilePath, profile));
      });

    },

    showFileDialog: function(saveAs) {

      var fileInput = this.refs.fileInput.getDOMNode();

      // Toggle 'save as' feature
      if(saveAs) {
        fileInput.nwsaveas = true;
      } else {
        fileInput.removeAttribute('nwsaveas');
      }

      return new Promise(function(resolve, reject) {

        fileInput.addEventListener('change', handleChange, false);
        fileInput.click();

        function handleChange(evt) {
          fileInput.removeEventListener('change', handleChange);
          var value = this.value;
          this.value = null;
          resolve(value);
        }

      });


    }

});

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

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