/**
  * Generate a checkbox which is controlled by a system boolean setting, if setting is configurable
  * (null) then show the checkbox, else disable the checkbox<br>
  * <b>NOTE:</b> the label for this checkbox must use an rsf:id of (rsfId + "_label")<br>
  * <b>NOTE:</b> the message key for the label must be ("evalsettings." + rsfId + ".label")
  *
  * @param parent the parent container
  * @param rsfId the rsf id of the checkbox
  * @param binding the EL binding for this control value
  * @param systemSetting the system setting value which controls this checkbox
  * @param form the form which the control is part of
  * @param disabled if true then disable the control, else it is enabled (for disabling based on
  *     state)
  */
 protected void generateSettingsControlledCheckbox(
     UIContainer parent,
     String rsfId,
     String binding,
     Boolean systemSetting,
     UIForm form,
     boolean disabled) {
   if (systemSetting == null) {
     UIBoundBoolean checkbox = UIBoundBoolean.make(parent, rsfId, binding);
     UIMessage.make(parent, rsfId + "_label", "evalsettings." + rsfId + ".label")
         .decorate(new UILabelTargetDecorator(checkbox));
     if (disabled) {
       RSFUtils.disableComponent(checkbox); // disable the control
     }
   } else {
     // bind the value explicitly
     form.parameters.add(new UIELBinding(binding, systemSetting));
     // now render the appropriate messages
     if (systemSetting) {
       UIMessage.make(parent, rsfId + "_label", "evalsettings." + rsfId + ".label");
     } else {
       UIMessage.make(parent, rsfId + "_label", "evalsettings." + rsfId + ".disabled");
     }
   }
 }
 /**
  * Reduces code duplication<br>
  * This will render the view date picker control or a message depending on various system settings
  * <br>
  * <b>NOTE:</b> the rsfId should not include the ":" even though it must appear in the template
  * with a colon<br>
  * <b>NOTE:</b> the label for this message must use an rsf:id of (rsfId + "_label")<br>
  *
  * @param parent the parent container
  * @param rsfId the rsf id of the checkbox
  * @param binding the EL binding for this control value
  * @param viewResultsSetting
  * @param useDateTime
  * @param sameViewDateForAll
  */
 protected void generateViewDateControl(
     UIBranchContainer parent,
     String rsfId,
     String binding,
     Boolean viewResultsSetting,
     Boolean useDateTime,
     boolean sameViewDateForAll) {
   if (viewResultsSetting == null || viewResultsSetting) {
     // only show something if this on or configurable
     if (sameViewDateForAll) {
       // just show the text to the user since all view dates are the same AND the system setting
       // forces this
       UIMessage.make(parent, rsfId + "_label", "evalsettings.view.results.date.label");
     } else {
       // allow them to choose the date using a date picker
       UIInput dateInput = UIInput.make(parent, rsfId + ":", binding);
       if (useDateTime) {
         dateevolver.setStyle(FormatAwareDateInputEvolver.DATE_TIME_INPUT);
       } else {
         dateevolver.setStyle(FormatAwareDateInputEvolver.DATE_INPUT);
       }
       dateevolver.evolveDateInput(dateInput);
     }
   }
 }
  /* (non-Javadoc)
   * @see uk.org.ponder.rsf.view.ComponentProducer#fillComponents(uk.org.ponder.rsf.components.UIContainer, uk.org.ponder.rsf.viewstate.ViewParameters, uk.org.ponder.rsf.view.ComponentChecker)
   */
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

    EvalViewParameters evalViewParams = (EvalViewParameters) viewparams;
    if (evalViewParams.evaluationId == null) {
      throw new IllegalArgumentException("Cannot access this view unless the evaluationId is set");
    }

    String actionBean = "setupEvalBean.";
    String evaluationOTP = "evaluationBeanLocator." + evalViewParams.evaluationId + ".";
    /**
     * This is the evaluation we are working with on this page, this should ONLY be read from, do
     * not change any of these fields
     */
    EvalEvaluation evaluation = evaluationService.getEvaluationById(evalViewParams.evaluationId);
    String currentEvalState = evaluationService.returnAndFixEvalState(evaluation, true);

    // local variables used in the render logic
    String currentUserId = commonLogic.getCurrentUserId();
    boolean userAdmin = commonLogic.isUserAdmin(currentUserId);
    boolean createTemplate = authoringService.canCreateTemplate(currentUserId);
    boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId);

    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG, locale);
    DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, locale);

    /*
     * top links here
     */
    UIInternalLink.make(
        tofill,
        "summary-link",
        UIMessage.make("summary.page.title"),
        new SimpleViewParameters(SummaryProducer.VIEW_ID));

    if (userAdmin) {
      UIInternalLink.make(
          tofill,
          "administrate-link",
          UIMessage.make("administrate.page.title"),
          new SimpleViewParameters(AdministrateProducer.VIEW_ID));
      UIInternalLink.make(
          tofill,
          "control-scales-link",
          UIMessage.make("controlscales.page.title"),
          new SimpleViewParameters(ControlScalesProducer.VIEW_ID));
    }

    if (createTemplate) {
      UIInternalLink.make(
          tofill,
          "control-templates-link",
          UIMessage.make("controltemplates.page.title"),
          new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID));
      UIInternalLink.make(
          tofill,
          "control-items-link",
          UIMessage.make("controlitems.page.title"),
          new SimpleViewParameters(ControlItemsProducer.VIEW_ID));
    }

    if (beginEvaluation) {
      UIInternalLink.make(
          tofill,
          "control-evaluations-link",
          UIMessage.make("controlevaluations.page.title"),
          new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID));
    } else {
      throw new SecurityException(
          "User attempted to access " + VIEW_ID + " when they are not allowed");
    }

    UIInternalLink.make(
        tofill,
        "eval-settings-link",
        UIMessage.make("evalsettings.page.title"),
        new EvalViewParameters(EvaluationSettingsProducer.VIEW_ID, evalViewParams.evaluationId));
    if (EvalConstants.EVALUATION_STATE_PARTIAL.equals(evaluation.getState())) {
      // creating a new eval
      UIMessage.make(tofill, "eval-start-text", "starteval.page.title");
    }

    UIForm form = UIForm.make(tofill, "evalSettingsForm");

    // REOPENING eval (SPECIAL CASE)
    Date reOpenDueDate = null;
    Date reOpenStopDate = null;
    boolean reOpening = false;
    if (evalViewParams.reOpening) {
      Boolean enableReOpen = (Boolean) settings.get(EvalSettings.ENABLE_EVAL_REOPEN);
      if (enableReOpen) {
        // check if already active, do nothing if not closed
        if (EvalUtils.checkStateAfter(
            currentEvalState, EvalConstants.EVALUATION_STATE_CLOSED, false)) {
          // force the due and stop dates to something reasonable
          Calendar calendar = new GregorianCalendar();
          calendar.setTime(new Date());
          calendar.add(Calendar.DATE, 1);
          reOpenDueDate = calendar.getTime();

          Boolean useStopDate = (Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE);
          if (useStopDate) {
            // assign stop date to equal due date for now
            reOpenStopDate = calendar.getTime();
          }

          // finally force the state to appear active
          currentEvalState = EvalConstants.EVALUATION_STATE_ACTIVE;
          form.parameters.add(
              new UIELBinding(actionBean + "reOpening", true)); // so we know we are reopening
          reOpening = true;
        }
      }
    }

    // EVALUATION TITLE/INSTRUCTIONS

    if (EvalUtils.checkStateBefore(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true)) {
      UIInput.make(form, "title", evaluationOTP + "title");
    } else {
      UIOutput.make(tofill, "title_disabled", evaluation.getTitle());
    }

    if (EvalUtils.checkStateBefore(currentEvalState, EvalConstants.EVALUATION_STATE_CLOSED, true)) {
      UIInput instructionsInput =
          UIInput.make(form, "instructions:", evaluationOTP + "instructions");
      instructionsInput.decorators = new DecoratorList(new UITextDimensionsDecorator(60, 4));
      richTextEvolver.evolveTextInput(instructionsInput);
    } else {
      UIVerbatim.make(tofill, "instructions_disabled", evaluation.getInstructions());
    }

    // only put up the controls/auto binding if this is not already set
    if (evaluation.getTemplate() == null) {
      // Make bottom table containing the list of templates if no template set
      if (evalViewParams.templateId == null) {
        // get the templates usable by this user
        List<EvalTemplate> templateList =
            authoringService.getTemplatesForUser(currentUserId, null, false);
        if (templateList.size() > 0) {
          UIBranchContainer chooseTemplate = UIBranchContainer.make(form, "chooseTemplate:");

          String[] values = new String[templateList.size()];
          String[] labels = new String[templateList.size()];

          // TODO - this is not a good way to do this
          UISelect radios =
              UISelect.make(
                  chooseTemplate, "templateRadio", null, null, actionBean + "templateId", null);
          String selectID = radios.getFullID();
          for (int i = 0; i < templateList.size(); i++) {
            EvalTemplate template = templateList.get(i);
            values[i] = template.getId().toString();
            labels[i] = template.getTitle();
            UIBranchContainer radiobranch =
                UIBranchContainer.make(chooseTemplate, "templateOptions:", i + "");
            UISelectChoice.make(radiobranch, "radioValue", selectID, i);
            UISelectLabel.make(radiobranch, "radioLabel", selectID, i);
            EvalUser owner = commonLogic.getEvalUserById(template.getOwner());
            UIOutput.make(radiobranch, "radioOwner", owner.displayName);
            UIInternalLink.make(
                radiobranch,
                "viewPreview_link",
                UIMessage.make("starteval.view.preview.link"),
                new EvalViewParameters(PreviewEvalProducer.VIEW_ID, null, template.getId()));
          }
          // need to assign the choices and labels at the end here since we used nulls at the
          // beginning
          radios.optionlist = UIOutputMany.make(values);
          radios.optionnames = UIOutputMany.make(labels);
        } else {
          throw new IllegalStateException(
              "User got to evaluation settings when they have no access to any templates... "
                  + "producer suicide was the only way out");
        }
      } else {
        // just bind in the template explicitly to the evaluation
        form.parameters.add(
            new UIELBinding(
                evaluationOTP + "template",
                new ELReference("templateBeanLocator." + evalViewParams.templateId)));
      }
    } else {
      EvalTemplate template = authoringService.getTemplateById(evaluation.getTemplate().getId());
      UIBranchContainer showTemplateBranch = UIBranchContainer.make(tofill, "showTemplate:");
      UIMessage.make(
          showTemplateBranch,
          "eval_template_title",
          "evalsettings.template.title.display",
          new Object[] {template.getTitle()});
      UIInternalLink.make(
          showTemplateBranch,
          "eval_template_preview_link",
          UIMessage.make("evalsettings.template.preview.link"),
          new EvalViewParameters(PreviewEvalProducer.VIEW_ID, null, template.getId()));
      if (!template.getLocked().booleanValue()
          && authoringService.canModifyTemplate(currentUserId, template.getId())) {
        UIInternalLink.make(
            showTemplateBranch,
            "eval_template_modify_link",
            UIMessage.make("general.command.edit"),
            new TemplateViewParameters(ModifyTemplateItemsProducer.VIEW_ID, template.getId()));
      }
    }

    // EVALUATION DATES

    Date today = new Date();
    UIMessage.make(
        tofill,
        "current_date",
        "evalsettings.dates.current",
        new Object[] {dateFormat.format(today), timeFormat.format(today)});

    // retrieve the global setting for use of date only or date and time picker
    Boolean useDateTime = (Boolean) settings.get(EvalSettings.EVAL_USE_DATE_TIME);

    // Start Date
    UIBranchContainer showStartDate = UIBranchContainer.make(form, "showStartDate:");
    generateDateSelector(
        showStartDate,
        "startDate",
        evaluationOTP + "startDate",
        null,
        currentEvalState,
        EvalConstants.EVALUATION_STATE_ACTIVE,
        useDateTime);

    // Due Date
    UIBranchContainer showDueDate = UIBranchContainer.make(form, "showDueDate:");
    generateDateSelector(
        showDueDate,
        "dueDate",
        evaluationOTP + "dueDate",
        reOpenDueDate,
        currentEvalState,
        EvalConstants.EVALUATION_STATE_GRACEPERIOD,
        useDateTime);

    // Stop Date - Show the "Stop date" text box only if allowed in the System settings
    Boolean useStopDate = (Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE);
    if (useStopDate) {
      UIBranchContainer showStopDate = UIBranchContainer.make(form, "showStopDate:");
      generateDateSelector(
          showStopDate,
          "stopDate",
          evaluationOTP + "stopDate",
          reOpenStopDate,
          currentEvalState,
          EvalConstants.EVALUATION_STATE_CLOSED,
          useDateTime);
    }

    // EVALUATION RESULTS VIEWING/SHARING

    // radio buttons for the results sharing options
    UISelect resultsSharingRadios =
        UISelect.make(
                form,
                "dummyRadioSharing",
                EvalToolConstants.EVAL_RESULTS_SHARING_VALUES,
                EvalToolConstants.EVAL_RESULTS_SHARING_LABELS_PROPS,
                evaluationOTP + "resultsSharing",
                null)
            .setMessageKeys();
    String resultsSharingId = resultsSharingRadios.getFullID();
    for (int i = 0; i < EvalToolConstants.EVAL_RESULTS_SHARING_VALUES.length; ++i) {
      UIBranchContainer radiobranch = UIBranchContainer.make(form, "resultsSharingChoice:", i + "");
      UISelectChoice choice = UISelectChoice.make(radiobranch, "radioValue", resultsSharingId, i);
      UISelectLabel.make(radiobranch, "radioLabel", resultsSharingId, i)
          .decorate(new UILabelTargetDecorator(choice));
    }

    // show the view date only if allowed by system settings
    if (((Boolean) settings.get(EvalSettings.EVAL_USE_VIEW_DATE)).booleanValue()) {
      UIBranchContainer showViewDate = UIBranchContainer.make(form, "showViewDate:");
      generateDateSelector(
          showViewDate,
          "viewDate",
          evaluationOTP + "viewDate",
          null,
          currentEvalState,
          EvalConstants.EVALUATION_STATE_VIEWABLE,
          useDateTime);
    }

    // all types of users view results on the same date or we can configure the results viewing
    // separately
    boolean sameViewDateForAll = (Boolean) settings.get(EvalSettings.EVAL_USE_SAME_VIEW_DATES);

    // Student view date
    Boolean studentViewResults = (Boolean) settings.get(EvalSettings.STUDENT_ALLOWED_VIEW_RESULTS);
    UIBranchContainer showResultsToStudents =
        UIBranchContainer.make(form, "showResultsToStudents:");
    generateSettingsControlledCheckbox(
        showResultsToStudents,
        "studentViewResults",
        evaluationOTP + "studentViewResults",
        studentViewResults,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_VIEWABLE, true));
    generateViewDateControl(
        showResultsToStudents,
        "studentsViewDate",
        evaluationOTP + "studentsDate",
        studentViewResults,
        useDateTime,
        sameViewDateForAll);

    // Instructor view date
    Boolean instructorViewResults =
        (Boolean) settings.get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS);
    UIBranchContainer showResultsToInst = UIBranchContainer.make(form, "showResultsToInst:");
    generateSettingsControlledCheckbox(
        showResultsToInst,
        "instructorViewResults",
        evaluationOTP + "instructorViewResults",
        instructorViewResults,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_VIEWABLE, true));
    generateViewDateControl(
        showResultsToInst,
        "instructorsViewDate",
        evaluationOTP + "instructorsDate",
        instructorViewResults,
        useDateTime,
        sameViewDateForAll);

    // RESPONDENT SETTINGS

    // Student Allowed Leave Unanswered
    Boolean studentUnanswersAllowed =
        (Boolean) settings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
    UIBranchContainer showBlankQuestionAllowedToStut =
        UIBranchContainer.make(form, "showBlankQuestionAllowedToStut:");
    generateSettingsControlledCheckbox(
        showBlankQuestionAllowedToStut,
        "blankResponsesAllowed",
        evaluationOTP + "blankResponsesAllowed",
        studentUnanswersAllowed,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true));

    // Student Modify Responses
    Boolean studentModifyReponses = (Boolean) settings.get(EvalSettings.STUDENT_MODIFY_RESPONSES);
    UIBranchContainer showModifyResponsesAllowedToStu =
        UIBranchContainer.make(form, "showModifyResponsesAllowedToStu:");
    generateSettingsControlledCheckbox(
        showModifyResponsesAllowedToStu,
        "modifyResponsesAllowed",
        evaluationOTP + "modifyResponsesAllowed",
        studentModifyReponses,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true));

    // ADMIN SETTINGS SECTION

    UISelect authControlSelect =
        UISelect.make(
                form,
                "auth-control-choose",
                EvalToolConstants.AUTHCONTROL_VALUES,
                EvalToolConstants.AUTHCONTROL_LABELS,
                evaluationOTP + "authControl")
            .setMessageKeys();
    if (EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true)) {
      RSFUtils.disableComponent(authControlSelect);
    }

    if (userAdmin) {
      // If the person is an admin (any kind), then we need to show these instructor opt in/out
      // settings

      UIMessage.make(
          form, "instructor-opt-instructions", "evalsettings.admin.settings.instructions");
      UIMessage.make(form, "instructor-opt-header", "evalsettings.instructor.opt.desc");

      // If "EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE" is set as configurable
      // i.e. NULL in the database then show the instructor opt select box. Else just show the value
      // as label
      String instUseFromAboveValue =
          (String) settings.get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE);
      if (instUseFromAboveValue == null
          || EvalToolConstants.ADMIN_BOOLEAN_CONFIGURABLE.equals(instUseFromAboveValue)) {
        UISelect instOpt =
            UISelect.make(
                    form,
                    "instructorOpt",
                    EvalToolConstants.INSTRUCTOR_OPT_VALUES,
                    EvalToolConstants.INSTRUCTOR_OPT_LABELS,
                    evaluationOTP + "instructorOpt")
                .setMessageKeys();
        if (EvalUtils.checkStateAfter(
            currentEvalState, EvalConstants.EVALUATION_STATE_INQUEUE, true)) {
          RSFUtils.disableComponent(instOpt);
        }
      } else {
        int index =
            ArrayUtil.indexOf(EvalToolConstants.INSTRUCTOR_OPT_VALUES, instUseFromAboveValue);
        String instUseFromAboveLabel = EvalToolConstants.INSTRUCTOR_OPT_LABELS[index];
        // Displaying the label corresponding to INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value set as
        // system property
        UIMessage.make(form, "instructorOptLabel", instUseFromAboveLabel);
        // Doing the binding of this INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value so that it can be
        // saved in the database
        form.parameters.add(
            new UIELBinding(evaluationOTP + "instructorOpt", instUseFromAboveValue));
      }
    }

    // EVALUATION REMINDERS SECTION

    // email available template link
    UIInternalLink.make(
        form,
        "emailAvailable_link",
        UIMessage.make("evalsettings.available.mail.link"),
        new EmailViewParameters(
            PreviewEmailProducer.VIEW_ID,
            null,
            EvalConstants.EMAIL_TEMPLATE_AVAILABLE,
            evaluation.getId()));

    // email reminder control
    UISelect reminderDaysSelect =
        UISelect.make(
                form,
                "reminderDays",
                EvalToolConstants.REMINDER_EMAIL_DAYS_VALUES,
                EvalToolConstants.REMINDER_EMAIL_DAYS_LABELS,
                evaluationOTP + "reminderDays")
            .setMessageKeys();
    if (EvalUtils.checkStateAfter(
        currentEvalState, EvalConstants.EVALUATION_STATE_GRACEPERIOD, true)) {
      RSFUtils.disableComponent(reminderDaysSelect);
    }

    // email reminder template link
    UIInternalLink.make(
        form,
        "emailReminder_link",
        UIMessage.make("evalsettings.reminder.mail.link"),
        new EmailViewParameters(
            PreviewEmailProducer.VIEW_ID,
            null,
            EvalConstants.EMAIL_TEMPLATE_REMINDER,
            evaluation.getId()));

    // email from address control
    String defaultEmail = (String) settings.get(EvalSettings.FROM_EMAIL_ADDRESS);
    UIMessage.make(
        form, "eval-from-email-note", "evalsettings.email.sent.from", new String[] {defaultEmail});
    UIInput.make(form, "reminderFromEmail", evaluationOTP + "reminderFromEmail");

    // EVALUATION EXTRAS SECTION
    Boolean categoriesEnabled = (Boolean) settings.get(EvalSettings.ENABLE_EVAL_CATEGORIES);
    if (categoriesEnabled) {
      UIBranchContainer extrasBranch = UIBranchContainer.make(form, "showEvalExtras:");

      // eval category
      if (categoriesEnabled) {
        UIBranchContainer categoryBranch = UIBranchContainer.make(extrasBranch, "showCategory:");
        UIInput.make(categoryBranch, "eval-category", evaluationOTP + "evalCategory");
        if (evaluation.getEvalCategory() != null) {
          UILink.make(
                  categoryBranch,
                  "eval-category-direct-link",
                  UIMessage.make("general.direct.link"),
                  commonLogic.getEntityURL(
                      EvalCategoryEntityProvider.ENTITY_PREFIX, evaluation.getEvalCategory()))
              .decorate(new UITooltipDecorator(UIMessage.make("general.direct.link.title")));
        }
      }
    }

    // EVAL SETTINGS SAVING CONTROLS
    // if this evaluation is already saved, show "Save Settings" button else this is the "Continue
    // to Assign to Courses" button
    String messageKey = "evalsettings.save.settings.link";
    if (EvalConstants.EVALUATION_STATE_PARTIAL.equals(evaluation.getState())) {
      messageKey = "evalsettings.continue.assigning.link";
    }
    if (reOpening) {
      messageKey = "evalsettings.reopening.eval.link";
    }
    UICommand.make(
        form,
        "continueAssigning",
        UIMessage.make(messageKey),
        actionBean + "completeSettingsAction");
    UIMessage.make(tofill, "cancel-button", "general.cancel.button");

    // this fills in the javascript call (areaId, selectId, selectValue, reminderId)
    // NOTE: RSF bug causes us to have to generate the ids manually
    // (http://www.caret.cam.ac.uk/jira/browse/RSF-65)
    UIInitBlock.make(
        tofill,
        "initJavascript",
        "EvalSystem.initEvalSettings",
        new Object[] {
          "evaluation_reminder_area",
          authControlSelect.getFullID() + "-selection",
          EvalConstants.EVALUATION_AUTHCONTROL_NONE,
          reminderDaysSelect.getFullID() + "-selection"
        });
  }
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

    String currentuserid = externalLogic.getCurrentUserId();

    PollViewParameters ecvp = (PollViewParameters) viewparams;
    Poll poll = null;
    boolean isNew = true;

    UIForm newPoll = UIForm.make(tofill, "add-poll-form");
    LOG.debug("Poll of id: " + ecvp.id);
    if (ecvp.id == null || "New 0".equals(ecvp.id)) {
      UIMessage.make(tofill, "new_poll_title", "new_poll_title");
      // build an empty poll
      LOG.debug("this is a new poll");
      poll = new Poll();
    } else {
      UIMessage.make(tofill, "new_poll_title", "new_poll_title_edit");

      String strId = ecvp.id;
      LOG.debug("got id of " + strId);
      poll = pollListManager.getPollById(Long.valueOf(strId));
      voteBean.setPoll(poll);
      newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId()));

      isNew = false;
    }

    if (!externalLogic.isUserAdmin()
        && !externalLogic.isAllowedInLocation(
            PollListManager.PERMISSION_ADD,
            externalLogic.getCurrentLocationReference(),
            externalLogic.getCurrentuserReference())) {
      tml.addMessage(new TargettedMessage("new_poll_noperms"));
      return;
    }

    // only display for exisiting polls
    if (!isNew) {
      // fill the options list
      UIBranchContainer actionBlock = UIBranchContainer.make(newPoll, "option-headers:");
      UIMessage.make(actionBlock, "options-title", "new_poll_option_title");
      UIInternalLink.make(
          actionBlock,
          "option-add",
          UIMessage.make("new_poll_option_add"),
          new OptionViewParameters(PollOptionProducer.VIEW_ID, null, poll.getPollId().toString()));

      List<Vote> votes = pollVoteManager.getAllVotesForPoll(poll);
      if (votes != null && votes.size() > 0) {
        LOG.debug("Poll has " + votes.size() + " votes");
        UIBranchContainer errorRow = UIBranchContainer.make(tofill, "error-row:", "0");
        UIMessage.make(errorRow, "error", "warn_poll_has_votes");
      }

      List<Option> options = pollListManager.getVisibleOptionsForPoll(poll.getPollId());
      for (int i = 0; i < options.size(); i++) {
        Option o = (Option) options.get(i);
        UIBranchContainer oRow =
            UIBranchContainer.make(actionBlock, "options-row:", o.getOptionId().toString());
        UIVerbatim.make(oRow, "options-name", o.getOptionText());

        UIInternalLink editOption =
            UIInternalLink.make(
                oRow,
                "option-edit",
                UIMessage.make("new_poll_option_edit"),
                new OptionViewParameters(PollOptionProducer.VIEW_ID, o.getOptionId().toString()));

        editOption.decorators =
            new DecoratorList(
                new UITooltipDecorator(
                    messageLocator.getMessage("new_poll_option_edit")
                        + ":"
                        + FormattedText.convertFormattedTextToPlaintext(o.getOptionText())));

        UIInternalLink deleteOption =
            UIInternalLink.make(
                oRow,
                "option-delete",
                UIMessage.make("new_poll_option_delete"),
                new OptionViewParameters(
                    PollOptionDeleteProducer.VIEW_ID, o.getOptionId().toString()));

        deleteOption.decorators =
            new DecoratorList(
                new UITooltipDecorator(
                    messageLocator.getMessage("new_poll_option_delete")
                        + ":"
                        + FormattedText.convertFormattedTextToPlaintext(o.getOptionText())));
      }
    }

    UIMessage.make(tofill, "new-poll-descr", "new_poll_title");
    UIMessage.make(tofill, "new-poll-question-label", "new_poll_question_label");
    UIMessage pollDescr = UIMessage.make(tofill, "new-poll-descr-label", "new_poll_descr_label");
    UIMessage.make(tofill, "new-poll-descr-label2", "new_poll_descr_label2");

    // UIMessage.make(tofill, "new-poll-open-label", "new_poll_open_label");
    // UIMessage.make(tofill, "new-poll-close-label", "new_poll_close_label");

    UIMessage.make(tofill, "new-poll-limits", "new_poll_limits");
    // UIMessage pollMin = UIMessage.make(tofill, "new-poll-min-limits", "new_poll_min_limits");
    // UIMessage pollMax =  UIMessage.make(tofill, "new-poll-max-limits", "new_poll_max_limits");

    // the form fields
    UIInput.make(newPoll, "new-poll-text", "#{poll.text}", poll.getText());

    if (!externalLogic.isMobileBrowser()) {
      // show WYSIWYG editor
      UIInput itemDescr =
          UIInput.make(
              newPoll,
              "newpolldescr:",
              "#{poll.details}",
              poll.getDetails()); // $NON-NLS-1$ //$NON-NLS-2$
      richTextEvolver.evolveTextInput(itemDescr);
      UILabelTargetDecorator.targetLabel(pollDescr, itemDescr);
    } else {
      // do not show WYSIWYG editor in the mobile view
      UIInput itemDescr =
          UIInput.make(
              newPoll,
              "newpolldescr_mobile",
              "#{poll.details}",
              poll.getDetails()); // $NON-NLS-1$ //$NON-NLS-2$
      UILabelTargetDecorator.targetLabel(pollDescr, itemDescr);
    }

    UIInput voteOpen =
        UIInput.make(newPoll, "openDate-iso8601", "poll.voteOpenStr", poll.getVoteOpenStr());
    UIInput voteClose =
        UIInput.make(newPoll, "closeDate-iso8601", "poll.voteCloseStr", poll.getVoteCloseStr());
    // UILabelTargetDecorator.targetLabel(pollOpen, voteOpen);
    // UILabelTargetDecorator.targetLabel(pollClose, voteClose);

    /*
     * access options
     */
    UIMessage pollAccessLabel =
        UIMessage.make(newPoll, "poll_access_label", "new_poll_access_label");
    UIBoundBoolean accessPublic =
        UIBoundBoolean.make(newPoll, "access-public", "poll.isPublic", poll.getIsPublic());
    UIMessage newPollAccessPublicLabel =
        UIMessage.make(newPoll, "new_poll_access_public_label", "new_poll_access_public");

    // SAK-25399: Do not display the public access by default
    if (!externalLogic.isShowPublicAccess()) {
      newPoll.remove(pollAccessLabel);
      newPoll.remove(accessPublic);
      newPoll.remove(newPollAccessPublicLabel);
    }

    String[] minVotes =
        new String[] {
          "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
        };
    String[] maxVotes =
        new String[] {
          "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
        };
    UISelect min =
        UISelect.make(
            newPoll,
            "min-votes",
            minVotes,
            "#{poll.minOptions}",
            Integer.toString(poll.getMinOptions()));
    UISelect max =
        UISelect.make(
            newPoll,
            "max-votes",
            maxVotes,
            "#{poll.maxOptions}",
            Integer.toString(poll.getMaxOptions()));

    /*
     * 	open - can be viewd at any time
     * 	never - not diplayed
     * 	afterVoting - after user has voted
     * 	afterClosing
     *
     */

    String[] values = new String[] {"open", "afterVoting", "afterClosing", "never"};
    String[] labels =
        new String[] {
          messageLocator.getMessage("new_poll_open"),
          messageLocator.getMessage("new_poll_aftervoting"),
          messageLocator.getMessage("new_poll_afterClosing"),
          messageLocator.getMessage("new_poll_never")
        };

    UISelect radioselect =
        UISelect.make(
            newPoll, "release-select", values, "#{poll.displayResult}", poll.getDisplayResult());

    radioselect.optionnames = UIOutputMany.make(labels);

    String selectID = radioselect.getFullID();
    // StringList optList = new StringList();
    UIMessage.make(newPoll, "add_results_label", "new_poll_results_label");
    for (int i = 0; i < values.length; ++i) {

      UIBranchContainer radiobranch =
          UIBranchContainer.make(newPoll, "releaserow:", Integer.toString(i));
      UISelectChoice choice = UISelectChoice.make(radiobranch, "release", selectID, i);
      UISelectLabel lb = UISelectLabel.make(radiobranch, "releaseLabel", selectID, i);
      UILabelTargetDecorator.targetLabel(lb, choice);
    }

    LOG.debug("About to close the form");
    newPoll.parameters.add(new UIELBinding("#{poll.owner}", currentuserid));
    String siteId = externalLogic.getCurrentLocationId();
    newPoll.parameters.add(new UIELBinding("#{poll.siteId}", siteId));

    if (isNew || poll.getPollOptions() == null || poll.getPollOptions().size() == 0) {
      UICommand.make(
          newPoll,
          "submit-new-poll",
          UIMessage.make("new_poll_saveoption"),
          "#{pollToolBean.processActionAdd}");
    } else {
      UICommand.make(
          newPoll,
          "submit-new-poll",
          UIMessage.make("new_poll_submit"),
          "#{pollToolBean.processActionAdd}");
    }

    UICommand cancel =
        UICommand.make(
            newPoll, "cancel", UIMessage.make("new_poll_cancel"), "#{pollToolBean.cancel}");
    cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel"));
    LOG.debug("Finished generating view");
  }
Beispiel #5
0
  public void fillComponents(UIContainer arg0, ViewParameters arg1, ComponentChecker arg2) {

    String state = "";

    // group
    Group g = null;
    // id for group
    String groupId = null;
    // title for group
    String groupTitle = null;
    // description for group
    String groupDescription = null;
    // member list for group
    Set<Member> groupMembers = new HashSet<>();
    // group provider id
    String groupProviderId = null;
    // list of group role provider ids
    List<String> groupRoleProviderRoles = null;

    UIForm groupForm = UIForm.make(arg0, "groups-form");

    String id = ((GroupEditViewParameters) arg1).id;
    if (id != null) {
      try {
        // SAK-29645
        if (handler.messages.size() == 0) {
          g = siteService.findGroup(id);
          groupId = g.getId();
          groupTitle = g.getTitle();
          groupDescription = g.getDescription();
          handler.allowViewMembership =
              Boolean.valueOf(g.getProperties().getProperty(Group.GROUP_PROP_VIEW_MEMBERS));
          groupMembers = g.getMembers();
          groupProviderId = g.getProviderGroupId();
          groupRoleProviderRoles = handler.getGroupProviderRoles(g);
          String joinableSet = g.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET);
          if (joinableSet != null && !"".equals(joinableSet.trim())) {
            handler.joinableSetName = joinableSet;
            handler.joinableSetNameOrig = joinableSet;
            handler.joinableSetNumOfMembers =
                g.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET_MAX);
            handler.allowPreviewMembership =
                Boolean.valueOf(
                    g.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET_PREVIEW));
            // set unjoinable.  Since you can't change this value at the group edit page, all groups
            // will have the same
            // value in the set.  Find another group in the same set (if exist) and set it to the
            // same value.
            for (Group group : handler.site.getGroups()) {
              String joinableSetName =
                  group.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET);
              if (joinableSetName != null && joinableSetName.equals(joinableSet)) {
                // we only need to find the first one since all are the same
                handler.unjoinable =
                    Boolean.valueOf(
                        group.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_UNJOINABLE));
                break;
              }
            }
          } else {
            handler.joinableSetName = "";
            handler.joinableSetNameOrig = "";
            handler.joinableSetNumOfMembers = "";
            handler.allowPreviewMembership = false;
            handler.unjoinable = false;
          }
        }
      } catch (Exception e) {
        M_log.debug(this + "fillComponents: cannot get group id=" + id, e);
      }
    } else {
      handler.resetParams();
    }

    // action button name: Add for adding new group, Update for editing exist group
    String addUpdateButtonName =
        id != null
            ? messageLocator.getMessage("editgroup.update")
            : messageLocator.getMessage("editgroup.new");
    String headerText =
        id == null
            ? messageLocator.getMessage("group.newgroup")
            : messageLocator.getMessage("group.editgroup");

    UIOutput.make(groupForm, "prompt", headerText);
    UIOutput.make(
        groupForm, "emptyGroupTitleAlert", messageLocator.getMessage("editgroup.titlemissing"));
    UIOutput.make(
        groupForm,
        "instructions",
        messageLocator.getMessage("editgroup.instruction", new Object[] {addUpdateButtonName}));

    UIOutput.make(groupForm, "group_title_label", messageLocator.getMessage("group.title"));
    UIInput.make(
        groupForm, "group_title", "#{SiteManageGroupSectionRoleHandler.title}", groupTitle);

    UIMessage groupDescrLabel =
        UIMessage.make(groupForm, "group_description_label", "group.description");
    UIInput groupDescr =
        UIInput.make(
            groupForm,
            "group_description",
            "#{SiteManageGroupSectionRoleHandler.description}",
            groupDescription);
    UILabelTargetDecorator.targetLabel(groupDescrLabel, groupDescr);

    // allow view membership:
    UIBoundBoolean viewMemCheckbox =
        UIBoundBoolean.make(
            groupForm,
            "allowViewMembership",
            "#{SiteManageGroupSectionRoleHandler.allowViewMembership}");
    UILabelTargetDecorator.targetLabel(
        UIMessage.make(groupForm, "allowViewMembership-label", "group.allow.view.membership"),
        viewMemCheckbox);

    // Joinable Set:
    UIMessage joinableSetLabel =
        UIMessage.make(groupForm, "group_joinable_set_label", "group.joinable.set");
    List<String> joinableSetValuesSet = new ArrayList<>();
    for (Group group : handler.site.getGroups()) {
      String joinableSet = group.getProperties().getProperty(Group.GROUP_PROP_JOINABLE_SET);
      if (joinableSet != null && !joinableSetValuesSet.contains(joinableSet)) {
        joinableSetValuesSet.add(joinableSet);
      }
    }
    Collections.sort(joinableSetValuesSet);
    List<String> joinableSetValues = new ArrayList<>();
    List<String> joinableSetNames = new ArrayList<>();
    joinableSetValues.add("");
    joinableSetNames.add(messageLocator.getMessage("none"));
    joinableSetValues.addAll(joinableSetValuesSet);
    joinableSetNames.addAll(joinableSetValuesSet);

    String[] joinableSetNamesArr = joinableSetNames.toArray(new String[joinableSetNames.size()]);
    String[] joinableSetValuesArr = joinableSetValues.toArray(new String[joinableSetValues.size()]);
    UISelect joinableSetSelect =
        UISelect.make(
            groupForm,
            "joinable-set",
            joinableSetValuesArr,
            joinableSetNamesArr,
            "SiteManageGroupSectionRoleHandler.joinableSetName");
    UILabelTargetDecorator.targetLabel(joinableSetLabel, joinableSetSelect);
    // joinable div:
    UIBranchContainer joinableDiv = UIBranchContainer.make(groupForm, "joinable-set-div:");
    if (handler.joinableSetName == null || "".equals(handler.joinableSetName)) {
      Map<String, String> hidden = new HashMap<>();
      hidden.put("display", "none");
      joinableDiv.decorate(new UICSSDecorator(hidden));
    }
    // Max members Row:
    UIMessage.make(joinableDiv, "group-max-members", "group.joinable.maxMembers2");
    UIInput.make(
        joinableDiv,
        "num-max-members",
        "SiteManageGroupSectionRoleHandler.joinableSetNumOfMembers");
    // allow preview row:
    UIBoundBoolean checkbox =
        UIBoundBoolean.make(
            joinableDiv,
            "allowPreviewMembership",
            "#{SiteManageGroupSectionRoleHandler.allowPreviewMembership}");
    UILabelTargetDecorator.targetLabel(
        UIMessage.make(joinableDiv, "allowPreviewMembership-label", "group.joinable.allowPreview"),
        checkbox);

    UIOutput.make(groupForm, "membership_label", messageLocator.getMessage("editgroup.membership"));
    UIOutput.make(
        groupForm, "membership_site_label", messageLocator.getMessage("editgroup.generallist"));
    UIOutput.make(
        groupForm, "membership_group_label", messageLocator.getMessage("editgroup.grouplist"));

    /** ******************** for the site members list ************************* */
    List<String> siteRosters = handler.getSiteRosters(g);
    List<Role> siteRoles = handler.getSiteRoles(g);
    List<Participant> siteMembers = handler.getSiteParticipant(g);
    List<String> siteMemberLabels = new ArrayList<>();
    List<String> siteMemberValues = new ArrayList<>();
    List<String> membersSelected;
    if (handler.memberList != null && handler.memberList.length() > 0) {
      membersSelected = Arrays.asList(handler.memberList.split("##"));
    } else {
      membersSelected = new ArrayList<>();
    }

    // add site roster
    for (String roster : siteRosters) {
      // not include in the group yet
      if ((groupProviderId == null || !groupProviderId.contains(roster))
          && !membersSelected.contains(roster)) {
        siteMemberLabels.add(SECTION_PREFIX + handler.getRosterLabel(roster) + " (" + roster + ")");
        siteMemberValues.add(roster);
      }
    }
    // add site role
    for (Role role : siteRoles) {
      // not include in the group yet
      if ((groupRoleProviderRoles == null || !groupRoleProviderRoles.contains(role.getId()))
          && !membersSelected.contains(role.getId())) {
        siteMemberLabels.add(ROLE_PREFIX + role.getId());
        siteMemberValues.add(role.getId());
      }
    }
    // add site members to the list
    Iterator<Participant> sIterator =
        new SortedIterator(
            siteMembers.iterator(),
            new SiteComparator(SiteConstants.SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString()));
    while (sIterator.hasNext()) {
      Participant p = (Participant) sIterator.next();
      // not in the group yet
      if ((g == null || g.getMember(p.getUniqname()) == null)
          && !membersSelected.contains(p.getUniqname())) {
        siteMemberLabels.add(p.getName() + " (" + p.getDisplayId() + ")");
        siteMemberValues.add(p.getUniqname());
      }
    }

    UISelect.makeMultiple(
        groupForm,
        "siteMembers",
        siteMemberValues.toArray(new String[siteMemberValues.size()]),
        siteMemberLabels.toArray(new String[siteMemberLabels.size()]),
        "#{SiteManageGroupSectionRoleHandler.selectedSiteMembers}",
        new String[] {});

    /** ******************** for the group members list ************************* */
    List<String> groupRosters = handler.getGroupRosters(g);
    List<String> groupProviderRoles = handler.getGroupProviderRoles(g);
    List<Member> groupMembersCopy = new ArrayList<>();
    groupMembersCopy.addAll(groupMembers);
    for (Member p : groupMembersCopy) {
      // exclude those user with provided roles and rosters
      String userId = p.getUserId();
      try {
        // get user
        User u = userDirectoryService.getUser(userId);
        if (handler.isUserFromProvider(u.getEid(), userId, g, groupRosters, groupProviderRoles)) {
          groupMembers.remove(p);
        }
      } catch (Exception e) {
        M_log.debug(this + "fillInComponent: cannot find user with id " + userId, e);
        // need to remove the group member
        groupMembers.remove(p);
      }
    }

    // SAK-29645
    List<String> groupMemberLabels = new ArrayList<>();
    List<String> groupMemberValues = new ArrayList<>();

    // add the rosters first
    if (groupRosters != null) {
      for (String groupRoster : groupRosters) {
        groupMemberLabels.add(SECTION_PREFIX + groupRoster);
        groupMemberValues.add(groupRoster);
      }
    }
    // add the roles next
    if (groupProviderRoles != null) {
      for (String groupProviderRole : groupProviderRoles) {
        groupMemberLabels.add(ROLE_PREFIX + groupProviderRole);
        groupMemberValues.add(groupProviderRole);
      }
    }
    // add the members last
    if (groupMembers != null) {
      Iterator<Member> gIterator =
          new SortedIterator(
              groupMembers.iterator(),
              new SiteComparator(SiteConstants.SORTED_BY_MEMBER_NAME, Boolean.TRUE.toString()));
      while (gIterator.hasNext()) {
        Member p = (Member) gIterator.next();
        String userId = p.getUserId();
        try {
          User u = userDirectoryService.getUser(userId);
          groupMemberLabels.add(u.getSortName() + " (" + u.getDisplayId() + ")");
          groupMemberValues.add(userId);
        } catch (Exception e) {
          M_log.debug(this + ":fillComponents: cannot find user " + userId, e);
        }
      }
    }

    // SAK-29645 - preserve user selected values
    if (!membersSelected.isEmpty()) {
      siteRosters = handler.getSiteRosters(null);
      List<String> siteRoleIDs = handler.getSiteRoleIds();
      for (String memberID : membersSelected) {
        // Selected roster...
        if (siteRosters.contains(memberID)) {
          groupMemberLabels.add(SECTION_PREFIX + memberID);
          groupMemberValues.add(memberID);
        }

        // Selected role...
        else if (siteRoleIDs.contains(memberID)) {
          groupMemberLabels.add(ROLE_PREFIX + memberID);
          groupMemberValues.add(memberID);
        }

        // Selected member...
        else if (groupMembers != null) {
          sIterator =
              new SortedIterator(
                  siteMembers.iterator(),
                  new SiteComparator(
                      SiteConstants.SORTED_BY_PARTICIPANT_NAME, Boolean.TRUE.toString()));
          while (sIterator.hasNext()) {
            Participant p = (Participant) sIterator.next();
            String userID = p.getUniqname();
            if (StringUtils.isNotBlank(userID) && userID.equals(memberID)) {
              groupMemberLabels.add(p.getName() + " (" + p.getDisplayId() + ")");
              groupMemberValues.add(userID);
            }
          }
        }
      }
    }

    UISelect.make(
        groupForm,
        "groupMembers",
        groupMemberValues.toArray(new String[groupMemberValues.size()]),
        groupMemberLabels.toArray(new String[groupMemberLabels.size()]),
        null);
    UICommand.make(
        groupForm,
        "save",
        addUpdateButtonName,
        "#{SiteManageGroupSectionRoleHandler.processAddGroup}");

    UICommand cancel =
        UICommand.make(
            groupForm,
            "cancel",
            messageLocator.getMessage("editgroup.cancel"),
            "#{SiteManageGroupSectionRoleHandler.processBack}");
    cancel.parameters.add(new UIDeletionBinding("#{destroyScope.resultScope}"));

    UIInput.make(groupForm, "newRight", "#{SiteManageGroupSectionRoleHandler.memberList}", state);

    // hidden field for group id
    UIInput.make(groupForm, "groupId", "#{SiteManageGroupSectionRoleHandler.id}", groupId);

    // process any messages
    tml = handler.messages;
    if (tml.size() > 0) {
      for (int i = 0; i < tml.size(); i++) {
        UIBranchContainer errorRow =
            UIBranchContainer.make(arg0, "error-row:", Integer.toString(i));
        TargettedMessage msg = tml.messageAt(i);
        if (msg.args != null) {
          UIMessage.make(errorRow, "error", msg.acquireMessageCode(), (Object[]) msg.args);
        } else {
          UIMessage.make(errorRow, "error", msg.acquireMessageCode());
        }
      }
    }

    frameAdjustingProducer.fillComponents(arg0, "resize", "resetFrame");
  }
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
    ViewSubmissionsViewParams params = (ViewSubmissionsViewParams) viewparams;
    // make sure that we have an AssignmentID to work with
    if (params.assignmentId == null) {
      // ERROR SHOULD BE SET, OTHERWISE TAKE BACK TO ASSIGNMENT_LIST
      messages.addMessage(new TargettedMessage("GeneralActionError"));
      return;
    }
    assignmentId = params.assignmentId;
    Assignment2 assignment = assignmentLogic.getAssignmentByIdWithAssociatedData(assignmentId);

    String currUserId = externalLogic.getCurrentUserId();

    boolean contentReviewEnabled =
        assignment.isContentReviewEnabled()
            && contentReviewLogic.isContentReviewAvailable(assignment.getContextId());

    // let's double check that none of the associated groups were deleted from the site
    boolean displayGroupDeletionWarning = false;
    if (assignment.getAssignmentGroupSet() != null
        && !assignment.getAssignmentGroupSet().isEmpty()) {
      Collection<Group> siteGroups = externalLogic.getSiteGroups(assignment.getContextId());
      List<String> groupIds = new ArrayList<String>();
      if (siteGroups != null) {
        for (Group group : siteGroups) {
          groupIds.add(group.getId());
        }
      }

      for (AssignmentGroup assignGroup : assignment.getAssignmentGroupSet()) {
        if (!groupIds.contains(assignGroup.getGroupId())) {
          displayGroupDeletionWarning = true;
          break;
        }
      }
    }

    if (displayGroupDeletionWarning) {
      UIOutput.make(
          tofill,
          "deleted_group",
          messageLocator.getMessage("assignment2.assignment_grade-assignment.group_deleted"));
    }

    // Edit Permission
    boolean userMayEditAssign =
        permissionLogic.isUserAllowedToEditAssignment(currUserId, assignment);
    boolean userMayManageSubmissions =
        permissionLogic.isUserAllowedToManageSubmissionsForAssignment(currUserId, assignment);

    // get parameters
    if (params.sort_by == null) params.sort_by = DEFAULT_SORT_BY;
    if (params.sort_dir == null) params.sort_dir = DEFAULT_SORT_DIR;

    UIVerbatim.make(
        tofill, "defaultSortBy", HTMLUtil.emitJavascriptVar("defaultSortBy", DEFAULT_SORT_BY));

    // we need to retrieve the history for the release/retract feedback logic
    List<AssignmentSubmission> submissions =
        submissionLogic.getViewableSubmissionsWithHistoryForAssignmentId(
            assignmentId, params.groupId);
    List<String> studentIdList = new ArrayList<String>();
    if (submissions != null) {
      for (AssignmentSubmission submission : submissions) {
        studentIdList.add(submission.getUserId());
      }
    }

    // The following is some code to populate the sort order/page size, if
    // it's already been put in session state by the entity provider.
    Long pagesize = null;
    String orderBy = null;
    Boolean ascending = null;
    ToolSession toolSession = sessionManager.getCurrentToolSession();
    if (toolSession.getAttribute(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR)
        != null) {
      Map attr =
          (Map)
              toolSession.getAttribute(
                  Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR);
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_PAGE_SIZE)) {
        pagesize =
            (Long)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_PAGE_SIZE);
      }
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ORDER_BY)) {
        orderBy =
            (String)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ORDER_BY);
      }
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ASCENDING)) {
        ascending =
            (Boolean)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ASCENDING);
      }
    }

    // if assign is graded, retrieve the gb details, if appropriate
    GradebookItem gbItem = null;
    boolean gbItemExists = false;
    boolean gradesReleased = false;
    // user may view the associated gradebook item
    boolean userMayViewGbItem = false;
    // user has grading privileges for this gb item
    boolean userMayGrade = false;
    boolean userMayReleaseGrades = false;

    if (assignment.isGraded() && assignment.getGradebookItemId() != null) {
      userMayViewGbItem =
          gradebookLogic.isCurrentUserAbleToViewGradebookItem(
              assignment.getContextId(), assignment.getGradebookItemId());

      if (userMayViewGbItem) {
        // user may grade if there is at least one gradable student among the submissions
        List<String> gradableStudents =
            gradebookLogic.getFilteredStudentsForGradebookItem(
                currUserId,
                assignment.getContextId(),
                assignment.getGradebookItemId(),
                AssignmentConstants.GRADE,
                studentIdList);
        userMayGrade = gradableStudents != null && !gradableStudents.isEmpty();
        userMayReleaseGrades = gradebookLogic.isCurrentUserAbleToEdit(assignment.getContextId());

        try {
          gbItem =
              gradebookLogic.getGradebookItemById(
                  assignment.getContextId(), assignment.getGradebookItemId());
          gbItemExists = true;
          gradesReleased = gbItem.isReleased();
        } catch (GradebookItemNotFoundException ginfe) {
          if (log.isDebugEnabled())
            log.debug("Gb item with id: " + assignment.getGradebookItemId() + " no longer exists!");
          gbItem = null;
        }
      }
    }

    // if user has grading privileges but item no longer exists, display warning
    // to user
    if (assignment.isGraded() && userMayViewGbItem && !gbItemExists) {
      UIOutput.make(
          tofill,
          "no_gb_item",
          messageLocator.getMessage("assignment2.assignment_grade-assignment.gb_item_deleted"));
    }

    // We need to check if it's a non electronic submission.  If it is, we don't want to have
    // the submitted columns appear (Submitted and Submission Status).
    // We pass in the boolean parameter nonElectronicSubmission to viewSubmission.js (specifically
    // snn2subview.init()),
    // where logic is there to use this parameter.
    boolean nonElectronicSubmission = false;

    if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_NON_ELECTRONIC) {
      nonElectronicSubmission = true;
    }

    UIInitBlock.make(
        tofill,
        "asnn2subview-init",
        "asnn2subview.init",
        new Object[] {
          assignmentId,
          externalLogic.getCurrentContextId(),
          placement.getId(),
          submissions.size(),
          assignment.isGraded(),
          contentReviewEnabled,
          nonElectronicSubmission,
          pagesize,
          orderBy,
          ascending,
          gradesReleased,
          params.pageIndex
        });

    // Breadcrumbs
    UIInternalLink.make(
        tofill,
        "breadcrumb",
        messageLocator.getMessage("assignment2.assignment_list-sortview.heading"),
        new SimpleViewParameters(ListProducer.VIEW_ID));
    UIMessage.make(
        tofill,
        "last_breadcrumb",
        "assignment2.assignment_grade-assignment.heading",
        new Object[] {assignment.getTitle()});

    // ACTION BAR
    boolean displayReleaseGrades = false;
    boolean displayReleaseFB = false;
    boolean displayDownloadAll = false;
    boolean displayUploadAll = false;

    if (userMayEditAssign || userMayManageSubmissions) {
      UIOutput.make(tofill, "navIntraTool");
    }

    // RELEASE GRADES
    // don't display this option if the gb item doesn't exist anymore
    if (userMayReleaseGrades && assignment.isGraded() && gbItemExists) {
      displayReleaseGrades = true;

      // determine if grades have been released yet
      String releaseLinkText =
          messageLocator.getMessage("assignment2.assignment_grade-assignment.grades.release");
      if (gradesReleased) {
        releaseLinkText =
            messageLocator.getMessage("assignment2.assignment_grade-assignment.grades.retract");
      }

      UIForm releaseGradesForm = UIForm.make(tofill, "release_grades_form");
      UICommand releaseGradesButton = UICommand.make(releaseGradesForm, "release_grades");

      UIOutput.make(tofill, "release_grades_li");
      UIInternalLink releaseGradesLink =
          UIInternalLink.make(tofill, "release_grades_link", releaseLinkText, viewparams);
      Map<String, String> idmap = new HashMap<String, String>();
      idmap.put(
          "onclick",
          "asnn2.releaseGradesDialog('"
              + releaseGradesButton.getFullID()
              + "', '"
              + assignment.getContextId()
              + "', '"
              + assignment.getGradebookItemId()
              + "', '"
              + !gradesReleased
              + "'); return false;");
      releaseGradesLink.decorate(new UIFreeAttributeDecorator(idmap));

      makeReleaseGradesDialog(gradesReleased, assignment, tofill);
    }

    // RELEASE FEEDBACK
    if (userMayManageSubmissions) {
      displayReleaseFB = true;
      makeReleaseFeedbackLink(tofill, params, submissions);
    }

    // DOWNLOAD ALL
    if (userMayManageSubmissions) {
      displayDownloadAll = true;

      ZipViewParams zvp = new ZipViewParams("zipSubmissions", assignmentId);
      UIInternalLink.make(
          tofill,
          "downloadall",
          UIMessage.make("assignment2.assignment_grade-assignment.downloadall.button"),
          zvp);
    }

    // UPLOAD GRADES & FEEDBACK
    if (userMayManageSubmissions) {
      displayUploadAll = true;

      AssignmentViewParams avp = new AssignmentViewParams("uploadall", assignmentId);
      if (assignment.isGraded() && gbItemExists && userMayGrade) {
        UIInternalLink.make(
            tofill,
            "uploadall",
            UIMessage.make("assignment2.uploadall.breadcrumb.upload.graded"),
            avp);
      } else {
        UIInternalLink.make(
            tofill,
            "uploadall",
            UIMessage.make("assignment2.uploadall.breadcrumb.upload.ungraded"),
            avp);
      }
    }

    // handle those pesky separators
    if (displayReleaseGrades && (displayReleaseFB || displayUploadAll || displayDownloadAll)) {
      UIOutput.make(tofill, "release_grades_sep");
    }

    if (displayReleaseFB && (displayUploadAll || displayDownloadAll)) {
      UIOutput.make(tofill, "release_feedback_sep");
    }

    if (displayDownloadAll && displayUploadAll) {
      UIOutput.make(tofill, "downloadall_sep");
    }

    UIMessage.make(tofill, "page-title", "assignment2.assignment_grade-assignment.title");

    // now make the "View By Sections/Groups" filter
    makeViewByGroupFilter(tofill, params, assignment);

    /*
     * Form for assigning a grade to all submissions without a grade.
     * Do not allow grading if gbItem is null - it must have been deleted
     */
    if (submissions != null
        && !submissions.isEmpty()
        && userMayGrade
        && assignment.isGraded()
        && gbItemExists) {
      createApplyToUngradedWidget(assignment, tofill, params, "unassigned-apply-form0:");
      createApplyToUngradedWidget(assignment, tofill, params, "unassigned-apply-form1:");
    }

    // Confirmation Dialogs
    // These are only added here for internationalization. They are not part
    // of a real form.
    UICommand.make(
        tofill,
        "release-feedback-confirm",
        UIMessage.make("assignment2.dialogs.release_all_feedback.confirm"));
    UICommand.make(
        tofill,
        "release-feedback-cancel",
        UIMessage.make("assignment2.dialogs.release_all_feedback.cancel"));

    UICommand.make(
        tofill,
        "retract-feedback-confirm",
        UIMessage.make("assignment2.dialogs.retract_all_feedback.confirm"));
    UICommand.make(
        tofill,
        "retract-feedback-cancel",
        UIMessage.make("assignment2.dialogs.retract_all_feedback.cancel"));
  }