/** @jsx React.DOM */
var React = require('react/addons');
var Reflux = require('reflux');
var cx = React.addons.classSet;

var ModalAction = require('./ModalAction');

var ModalStore = require('./ModalStore');
 
var Modal = React.createClass({

  mixins: [Reflux.ListenerMixin],

  propTypes: {
    id: React.PropTypes.string.isRequired,
  },

  getInitialState: function() {
    return {
      visibility: false
    };
  },

  componentDidMount: function() {
    this.listenTo(ModalStore, this.updateVisibility);
    document.addEventListener('keyup', this.handleDocumentKeyUp);

    ModalAction.register(this.props.id);
  },

  componentWillUnmount: function() {
    document.removeEventListener('keyup', this.handleDocumentKeyUp);

    ModalAction.unregister(this.props.id);
  },

  updateVisibility: function() {
    this.setState({
      visibility: ModalStore.isOpen(this.props.id)
    });
  },

  hide: function() {
    ModalAction.close(this.props.id);
  },

  render: function() {
    var classes = {
      "reveal-modal": true,
      "completed": true,
      "open": this.state.visibility,
      "animatable": true,
      "slide-in-right": true,
      "active": this.state.visibility
    };

    var style = {
      opacity: 1,
      display: this.state.visibility ? "block" : "none",
      "zIndex": 300,
      "pointerEvents": "auto"
    };

    return (
      <span>
        <div onClick={this.handleBackdropClick} className="reveal-modal-bg" style={style}></div>
        <div className={cx(classes)}>
          <a className="close-reveal-modal">&#215;</a>
          {this.props.children}
        </div>
      </span>
    );
  },

  handleBackdropClick: function (e) {
    if (e.target !== e.currentTarget) {
      return;
    }

    this.hide();
  },

  handleDocumentKeyUp: function (e) {
    // Escape
    if (e.keyCode === 27) {
      this.hide();
    }
  }

});

module.exports = Modal;