/**
   * Generates the url string that users need to go to start the project
   *
   * @param httpRestTransport
   * @param request request that was made
   * @param run <code>Run</code> that the user is in
   * @param workgroup <code>Workgroup</code> that the user is in
   * @param retrieveAnnotationBundleUrl
   * @returnurl String url representation to download the jnlp and start the project
   */
  @Override
  public String generateStudentStartProjectUrlString(
      HttpRestTransport httpRestTransport,
      HttpServletRequest request,
      Run run,
      Workgroup workgroup,
      String retrieveAnnotationBundleUrl) {
    String jnlpUrl = generateLaunchProjectUrlString(httpRestTransport, run, workgroup);

    String entireUrl =
        jnlpUrl + "?" + generateRetrieveAnnotationBundleParamRequestString(request, workgroup);

    // TODO HT: put these param-generation into run/project domain object as much as possible to
    // stop
    // cluttering services
    // add jnlp.portal_baseurl and jnlp.runId to the request
    entireUrl += "&" + generatePortalBaseUrlParamRequestString(request);
    entireUrl += "&" + generateRunIdParamRequestString(run.getId());
    if (run.getProject().getFamilytag().equals(FamilyTag.UCCP)) {
      entireUrl += "&jnlp.style=UCCP";
    }

    Curnit curnit = run.getProject().getCurnit();
    String curnitOtmlUrl = "";
    try {
      curnitOtmlUrl =
          ((OtmlModuleImpl) this.moduleService.getById(curnit.getId())).getRetrieveotmlurl();
    } catch (ObjectNotFoundException e) {

    }
    entireUrl += "&sailotrunk.otmlurl=" + curnitOtmlUrl;

    return entireUrl;
  }
  /**
   * Creates a run based on input parameters provided.
   *
   * @param runParameters
   * @return The run created.
   * @throws CurnitNotFoundException
   */
  @Transactional(rollbackFor = {HttpStatusCodeException.class})
  public Run createRun(RunParameters runParameters) throws ObjectNotFoundException {
    Project project = runParameters.getProject();
    // Project projectCopy = projectService.copyProject(project);
    Run run = new RunImpl();
    run.setEndtime(null);
    run.setStarttime(Calendar.getInstance().getTime());
    run.setRuncode(generateUniqueRunCode());
    run.setOwners(runParameters.getOwners());
    run.setMaxWorkgroupSize(runParameters.getMaxWorkgroupSize());
    run.setProject(project);

    // use the project name for the run name
    run.setName("" + runParameters.getProject().getName());

    Calendar reminderCal = Calendar.getInstance();
    reminderCal.add(Calendar.DATE, 30);
    run.setArchiveReminderTime(reminderCal.getTime());
    if (!(run.getProject() instanceof ExternalProject)) {
      if (run.getProject().getProjectType() != ProjectType.ROLOO
          && run.getProject().getProjectType() != ProjectType.LD) {
        run.setSdsOffering(generateSdsOfferingFromParameters(runParameters));
      }
    }
    Set<String> periodNames = runParameters.getPeriodNames();
    if (periodNames != null) {
      Set<Group> periods = new TreeSet<Group>();
      for (String periodName : runParameters.getPeriodNames()) {
        Group group = new PersistentGroup();
        group.setName(periodName);
        this.groupDao.save(group);
        periods.add(group);
      }
      run.setPeriods(periods);
    }
    run.setPostLevel(runParameters.getPostLevel());

    /* if this is an LD project take snapshot of project for run and set versionId
    if(run.getProject().getProjectType()==ProjectType.LD){
    	String requester = run.getOwners().iterator().next().getUserDetails().getUsername();
    	String versionId = this.projectService.takeSnapshot(run.getProject(), requester, "For Run " + run.getName());
    	if(versionId==null || versionId.equals("failed")){
    		throw new ObjectNotFoundException("Snapshot of project failed when creating the run.", RunImpl.class);
    	} else{
    		run.setVersionId(versionId);
    	}
    }
    */

    this.runDao.save(run);
    this.aclService.addPermission(run, BasePermission.ADMINISTRATION);
    return run;
  }
  /**
   * Set the project meta data into the request as an attribute so that we can access it in other
   * controllers
   *
   * @param run
   * @param request
   */
  private void setProjectMetaData(Run run, HttpServletRequest request) {
    Project project = run.getProject();
    ProjectMetadata metadata = project.getMetadata();
    String projectMetaDataJSONString = metadata.toJSONString();

    request.setAttribute("projectMetaData", projectMetaDataJSONString);
  }
  /**
   * Set the project path into the request as an attribute so that we can access it in other
   * controllers
   *
   * @param run
   * @param request
   */
  private void setProjectPath(Run run, HttpServletRequest request) {
    String curriculumBaseDir = portalProperties.getProperty("curriculum_base_dir");
    String rawProjectUrl =
        (String) run.getProject().getCurnit().accept(new CurnitGetCurnitUrlVisitor());
    String projectPath = curriculumBaseDir + rawProjectUrl;

    request.setAttribute("projectPath", projectPath);
  }
  private void handleStudentAssetManager(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletContext servletContext2 = this.getServletContext();
    ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper");
    User user = ControllerUtil.getSignedInUser();
    String studentuploads_base_dir = portalProperties.getProperty("studentuploads_base_dir");

    try {
      // get the run
      String runId = request.getParameter("runId");
      Run run = runService.retrieveById(new Long(runId));

      // get the project id
      Project project = run.getProject();
      Serializable projectId = project.getId();

      // set the project id into the request so the vlewrapper controller has access to it
      request.setAttribute("projectId", projectId + "");

      // get the workgroup id
      List<Workgroup> workgroupListByOfferingAndUser =
          workgroupService.getWorkgroupListByOfferingAndUser(run, user);
      Workgroup workgroup = workgroupListByOfferingAndUser.get(0);
      Long workgroupId = workgroup.getId();

      // set the workgroup id into the request so the vlewrapper controller has access to it
      request.setAttribute(
          "dirName",
          run.getId()
              + "/"
              + workgroupId
              + "/unreferenced"); // looks like /studentuploads/[runId]/[workgroupId]/unreferenced
      String commandParamter = request.getParameter("command");
      if (commandParamter != null && "studentAssetCopyForReference".equals(commandParamter)) {
        request.setAttribute(
            "referencedDirName",
            run.getId()
                + "/"
                + workgroupId
                + "/referenced"); // if we're copying student asset for reference, also pass along
                                  // the referenced dir. looks like
                                  // /studentuploads/[runId]/[workgroupId]/referenced
      }
      if (studentuploads_base_dir != null) {
        request.setAttribute("studentuploads_base_dir", studentuploads_base_dir);
      }
      // forward the request to the vlewrapper controller
      RequestDispatcher requestDispatcher =
          vlewrappercontext.getRequestDispatcher("/vle/studentassetmanager.html");
      requestDispatcher.forward(request, response);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (ObjectNotFoundException e) {
      e.printStackTrace();
    }
  }
  @Override
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {
    Workgroup workgroup =
        this.workgroupService.retrieveById(Long.parseLong(request.getParameter(WORKGROUPID)));
    Run run = this.runService.retrieveById(Long.parseLong(request.getParameter(RUNID)));
    RooloOtmlModuleImpl mod =
        (RooloOtmlModuleImpl) this.moduleService.getById(run.getProject().getCurnit().getId());
    IELO elo = this.moduleService.getEloForModule(mod);
    mod.setElo(elo);

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject(RUN, run);
    modelAndView.addObject(WORKGROUP, workgroup);
    modelAndView.addObject(PREVIEW, request.getParameter(PREVIEW));
    modelAndView.addObject(ELO, mod.getElo());

    return modelAndView;
  }
  private void handleViewStudentAssets(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletContext servletContext2 = this.getServletContext();
    ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper");
    User user = ControllerUtil.getSignedInUser();
    String studentuploads_base_dir = portalProperties.getProperty("studentuploads_base_dir");

    try {
      // get the run
      String runId = request.getParameter("runId");
      Run run = runService.retrieveById(new Long(runId));

      // get the project id
      Project project = run.getProject();
      Serializable projectId = project.getId();

      // set the project id into the request so the vlewrapper controller has access to it
      request.setAttribute("projectId", projectId + "");

      // set the workgroup id into the request so the vlewrapper controller has access to it
      if (studentuploads_base_dir != null) {
        request.setAttribute("studentuploads_base_dir", studentuploads_base_dir);
      }

      // workgroups is a ":" separated string of workgroups
      String workgroups = request.getParameter("workgroups");

      request.setAttribute("dirName", workgroups);

      // forward the request to the vlewrapper controller
      RequestDispatcher requestDispatcher =
          vlewrappercontext.getRequestDispatcher("/vle/studentassetmanager.html");
      requestDispatcher.forward(request, response);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (ObjectNotFoundException e) {
      e.printStackTrace();
    }
  }
  private void handleIdeaBasket(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletContext servletContext2 = this.getServletContext();
    ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper");
    User signedInUser = ControllerUtil.getSignedInUser();
    String action = request.getParameter("action");

    try {
      // get the run
      String runId = request.getParameter("runId");
      Run run = runService.retrieveById(new Long(runId));

      // get the project id
      Project project = run.getProject();
      Serializable projectId = project.getId();

      // set the project id into the request so the vlewrapper controller has access to it
      request.setAttribute("projectId", projectId + "");

      // get the authorities for the signed in user
      MutableUserDetails signedInUserDetails = signedInUser.getUserDetails();
      Collection<? extends GrantedAuthority> authorities = signedInUserDetails.getAuthorities();

      boolean isAdmin = false;
      boolean isTeacher = false;
      boolean isStudent = false;

      // this value will determine whether the user can modify anything they want in the public idea
      // basket
      boolean isPrivileged = false;

      for (GrantedAuthority authority : authorities) {
        if (authority.getAuthority().equals(UserDetailsService.ADMIN_ROLE)) {
          // user is an admin or teacher
          isAdmin = true;
          isPrivileged = true;
        } else if (authority.getAuthority().equals(UserDetailsService.TEACHER_ROLE)) {
          // user is an admin or teacher
          isTeacher = true;
          isPrivileged = true;
        }
      }

      if (!isTeacher) {
        isStudent = true;
      }

      request.setAttribute("isPrivileged", isPrivileged);

      if (isAdmin) {
        // user is an admin so we do not need to retrieve the workgroup id
      } else if (isTeacher) {
        // user is a teacher so we will retrieve their workgroup id for the run

        // get the workgroup id
        List<Workgroup> workgroupListByOfferingAndUser =
            workgroupService.getWorkgroupListByOfferingAndUser(run, signedInUser);
        // add nullpointer check
        Workgroup workgroup = workgroupListByOfferingAndUser.get(0);
        Long signedInWorkgroupId = workgroup.getId();

        // set the workgroup id into the request so the vlewrapper controller has access to it
        request.setAttribute("signedInWorkgroupId", signedInWorkgroupId + "");
      } else if (isStudent) {
        /*
         * the user is a student so we will make sure the run id
         * matches the run they are currently working on and then
         * retrieve their workgroup id for the run
         */

        HashMap<String, Run> studentsToRuns =
            (HashMap<String, Run>)
                request.getSession().getServletContext().getAttribute("studentsToRuns");

        String sessionId = request.getSession().getId();

        if (studentsToRuns != null && studentsToRuns.containsKey(sessionId)) {
          Run sessionRun = studentsToRuns.get(sessionId);
          Long sessionRunId = sessionRun.getId();

          if (sessionRunId.equals(new Long(runId))) {
            // get the workgroup id
            List<Workgroup> workgroupListByOfferingAndUser =
                workgroupService.getWorkgroupListByOfferingAndUser(run, signedInUser);
            // add nullpointer check
            Workgroup workgroup = workgroupListByOfferingAndUser.get(0);
            Long signedInWorkgroupId = workgroup.getId();

            // set the workgroup id into the request so the vlewrapper controller has access to it
            request.setAttribute("signedInWorkgroupId", signedInWorkgroupId + "");
          } else {
            // run id does not match the run that the student is logged in to
            response.sendError(
                HttpServletResponse.SC_UNAUTHORIZED,
                "Run id does not match run that student is logged in to");
            return;
          }
        } else {
          // session id was not found which means the session probably timed out
          response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Session no longer valid");
          return;
        }
      }

      // forward the request to the vlewrapper controller
      RequestDispatcher requestDispatcher =
          vlewrappercontext.getRequestDispatcher("/ideaBasket.html");
      requestDispatcher.forward(request, response);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (ObjectNotFoundException e) {
      e.printStackTrace();
    }
  }