/**
   * Creates a notification to a Group coordinator signaling that a user wants to join their group
   *
   * <p>- Requires a groupId request parameter for the GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void inviteAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<String, Object>();

    int groupId = Integer.parseInt(req.getParameter("groupId"));

    try {

      // Get the session user
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      User user = userSession.getUser();

      // Get the coordinator for the group
      GroupManager groupMan = new GroupManager();
      Group group = groupMan.get(groupId);
      User coordinator = groupMan.getCoordinator(groupId);

      // Send a notification to the coordinator for them to permit access to the group
      NotificationManager notificationMan = new NotificationManager();
      Notification notification =
          new Notification(
              coordinator.getId(),
              coordinator,
              groupId,
              group,
              user.getFullName() + " wants to join your group " + group.getGroupName(),
              "/home/notifications?addUserId=" + user.getId() + "&groupId=" + group.getId());
      notificationMan.createNotification(notification);

      redirectToLocal(req, res, "/home/dashboard");
      return;

    } catch (Exception e) {
      redirectToLocal(req, res, "/home/dashboard");
    }
  }
  /*
   * Add a new record to the Organization table,
   * creates an admin account when SA creates a new consulting company
   * @param OrganizationCode (based on Company Name)
   * @param OrganizationName (based on Company Description)
   * @param FKCompanyID
   * @param NameSequence
   * @param PKUser
   * @param nomRater
   * @throws SQLException
   * @throws Exception
   * @author: Mark Oei
   * @since v.1.3.12.63 09 Mar 2010
   */
  public boolean addOrganisationByCons(
      String OrganizationCode,
      String OrganizationName,
      int FKCompanyID,
      int NameSequence,
      int PKUser,
      String nomRater)
      throws SQLException, Exception {
    Connection con = null;
    Statement st = null;

    boolean bIsAdded = false;

    String sql =
        "INSERT INTO tblOrganization (OrganizationCode, OrganizationName, FKCompanyID, NameSequence, NominationModule)";
    sql =
        sql
            + " VALUES ('"
            + OrganizationCode
            + "', '"
            + OrganizationName
            + "', "
            + FKCompanyID
            + ", "
            + NameSequence
            + ", '"
            + Boolean.parseBoolean(nomRater)
            + "')";
    try {
      con = ConnectionBean.getConnection();
      st = con.createStatement();
      int iSuccess = st.executeUpdate(sql);
      System.out.println(iSuccess);
      if (iSuccess != 0) bIsAdded = true;
    } catch (Exception E) {
      System.err.println("Organization.java - AddRecord - " + E);
    } finally {
      ConnectionBean.closeStmt(st); // Close statement
      ConnectionBean.close(con); // Close connection
    }

    System.out.println("1. Add Organization");

    // add default under the organization.
    String defaultName = "NA";
    int FKOrganization = checkOrgExist(OrganizationCode, OrganizationName, FKCompanyID);
    // Change to disable print statement. Used for debugging only
    // Mark Oei 19 Mar 2010
    // System.out.println("testing " + FKOrganization);
    System.out.println("2. Check Organization Exist");
    if (FKOrganization != 0) {
      // Add Division
      div.addRecord(defaultName, FKOrganization, PKUser);
      System.out.println("3. Add Division");
      // Add Department
      dept.addRecord(defaultName, FKOrganization, PKUser);
      System.out.println("4. Add Department");
      // Add Group
      G.addRecord(defaultName, FKOrganization, PKUser);
      System.out.println("5. Add Group");
      // Check whether exists
      int FKDivision = div.checkDivExist(defaultName, FKOrganization);
      int FKDepartment = dept.checkDeptExist(defaultName, FKOrganization);
      int FKGroup = G.checkGroupExist(defaultName, FKOrganization);
      // Create links
      dept.linkDepartment(FKDivision, FKDepartment);
      G.linkGroup(FKDepartment, FKGroup);
      // Establish new admin account and password
      Date timeStamp = new java.util.Date();
      SimpleDateFormat dFormat = new SimpleDateFormat("ddMMyyHHmmss");
      String temp = dFormat.format(timeStamp);
      String loginName = OrganizationCode + "admin";
      String password = OrganizationCode + temp;
      int userType = 6;
      // Insert record into database
      U.addRecord(
          FKDepartment,
          FKDivision,
          userType,
          "Admin",
          "Admin",
          loginName,
          "NA",
          "NA",
          FKGroup,
          password,
          1,
          FKCompanyID,
          FKOrganization,
          "NA",
          PKUser);

      System.out.println("6. Add User");
      int userExist =
          U.checkUserExist(
              FKDepartment,
              FKDivision,
              userType,
              "Admin",
              "Admin",
              loginName,
              "NA",
              "NA",
              FKGroup,
              password,
              1,
              FKCompanyID,
              FKOrganization);

      System.out.println(
          "FKDivision = "
              + FKDivision
              + ", FKDepartment = "
              + FKDepartment
              + ", FKGroup = "
              + FKGroup
              + " and User Exist = "
              + userExist);

      if (userExist != 0) {
        try {
          U.insertRelation(userExist, userExist, 0);
        } catch (SQLException SE) {
          System.out.println(SE.getMessage());
        }
        // Send email notification
        String content = template.ForgotPass_temp(loginName, password);
        String email = "*****@*****.**";
        // Edited By Roger 13 June 2008
        Email.sendMail(
            server.getAdminEmail(),
            email,
            "New Admin Assignment for " + OrganizationName,
            content,
            FKOrganization);
      }

      System.out.println("8. Add User Relation");
    }

    sDetail = detail.getUserDetail(PKUser);
    ev.addRecord("Insert", itemName, OrganizationName, sDetail[2], sDetail[11], sDetail[10]);

    return bIsAdded;
  } // End Method for addOrganisationByCons
  /**
   * Displays a given Research Group page for a HTTP Get, or creates a new Group for a HTTP Post
   *
   * <p>- Requires a cookie for the session user - Requires a groupId request parameter for a GET -
   * Requires a groupName, description, createdByUserId request parameters for a POST
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void researchgroupAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<String, Object>();
    viewData.put("title", "Research Group");

    if (req.getMethod() == HttpMethod.Get) {
      // Load group data into Map
      GroupManager gm = new GroupManager();
      int groupId = Integer.parseInt(req.getParameter("groupId"));
      Group group = gm.get(groupId);

      if (group != null) {
        // Load Group into map
        viewData.put("group", group);

        // Load group members into Map
        List<String> groupMembers = gm.getGroupMembers(groupId);
        viewData.put("groupMembers", groupMembers);

        // Load meetings into map
        MeetingManager meetMan = new MeetingManager();
        List<Meeting> groupMeetings = meetMan.getGroupMeetings(groupId);
        viewData.put("groupMeetings", groupMeetings);

        // Load Document Data into Map
        DocumentManager docMan = new DocumentManager();
        List<Document> groupDocuments = docMan.getGroupDocuments(groupId);
        viewData.put("groupDocuments", groupDocuments);

        // Load discussion threads
        DiscussionManager dm = new DiscussionManager();
        viewData.put("groupDiscussions", dm.getThreads(groupId));

        // Check if the user is a member
        boolean isMember = false;
        HttpSession session = req.getSession();
        Session userSession = (Session) session.getAttribute("userSession");
        User user = userSession.getUser();

        for (Group g : gm.getAllGroups(user.getId())) {
          if (g.getId() == group.getId()) {
            isMember = true;
            break;
          }
        }

        viewData.put("notMember", !isMember);

        // View group page.
        view(req, res, "/views/group/ResearchGroup.jsp", viewData);

      } else {
        httpNotFound(req, res);
      }

    } else if (req.getMethod() == HttpMethod.Post) {
      // Create Group

      // Get data from parameters
      String groupName = req.getParameter("groupName");
      String description = req.getParameter("description");
      int adminId = Integer.parseInt(req.getParameter("createdByUserId"));

      // Create the Group
      GroupManager groupMan = new GroupManager();
      Group group = new Group();
      group.setGroupName(groupName);
      group.setDescription(description);
      group.setCoordinatorId(adminId);
      // Create the mapping
      groupMan.createGroup(group);
      int groupId = groupMan.getIdFor(group);
      groupMan.createMapping(groupId, adminId);

      group.setId(groupId);

      // Update the User Session to show new group
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      User admin = userSession.getUser();
      admin.getGroups().add(group);

      // Show the Group Page
      viewData.put("groupName", group.getGroupName());
      List<String> groupMembers = groupMan.getGroupMembers(groupId);
      viewData.put("groupMembers", groupMembers);

      view(req, res, "/views/group/ResearchGroup.jsp", viewData);
    }
  }