// This is the top level component that really decides upon the major page
// components to use. We start by deciding to show the login screen or a
// normal page, which constitutes a header along with some other content.

var CreateProject = require('./CreateProject.jsx');
var Location = require('../stores/Location');
var Login = require('./Login.jsx');
var React = require('react');
var Session = require('../stores/Session');
var ProjectDetails = require('./ProjectDetails.jsx');
var ProjectList = require('./ProjectList.jsx');
var Header = require('./Header.jsx');

var ProjectManagement = React.createClass({
  getInitialState: function() {
    return {
      hasSession: Session.hasSession(),
      location: Location.getLocation()
    };
  },

  componentDidMount: function() {
    Session.addLoggedInListener(this.updateSession);
    Session.addLoggedOutListener(this.updateSession);
    Location.addNewLocationListener(this.updateLocation);
  },

  componentWillUnmount: function() {
    Session.removeLoggedInListener(this.updateSession);
    Session.removeLoggedOutListener(this.updateSession);
    Location.removeNewLocationListener(this.updateLocation);
  },

  render: function () {
    if (this.state.hasSession) {

      var page = null;
      if (this.state.location.projectList) {
        page = <ProjectList />;
      } else if (this.state.location.project) {
        page = <ProjectDetails />;
      } else if (this.state.location.createProject) {
        page = <CreateProject />;
      }

      return (
        <div>
          <Header />
          { page }
        </div>
      );
    } else {
      return (
        <Login />
      )
    }
  },

  updateSession: function() {
    this.setState({ hasSession: Session.hasSession() });
  },

  updateLocation: function() {
    this.setState({ location: Location.getLocation() });
  }
});

module.exports = ProjectManagement;
