/**
  * This method is to delete alert
  *
  * @param formBase
  * @param result
  * @param request
  * @param response
  * @return ModelAndView
  */
 @RequestMapping(params = "methodToCall=approveAlert")
 public ModelAndView approveAlert(
     @ModelAttribute("KualiForm") DocumentFormBase formBase,
     BindingResult result,
     HttpServletRequest request,
     HttpServletResponse response) {
   AlertBo alertBo = null;
   MaintenanceDocumentForm maintenanceDocumentForm = (MaintenanceDocumentForm) formBase;
   OlePersistableBusinessObjectBase olePersistableBusinessObjectBase =
       (OlePersistableBusinessObjectBase)
           maintenanceDocumentForm.getDocument().getNewMaintainableObject().getDataObject();
   int index =
       Integer.parseInt(
           maintenanceDocumentForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
   olePersistableBusinessObjectBase.getAlertBoList().get(index).setAlertStatus(false);
   olePersistableBusinessObjectBase
       .getAlertBoList()
       .get(index)
       .setAlertModifierId(GlobalVariables.getUserSession().getPrincipalId());
   if (olePersistableBusinessObjectBase.getAlertBoList().get(index).isRepeatable()) {
     alertBo =
         alertHelperService.createNewAlertBo(
             olePersistableBusinessObjectBase.getAlertBoList().get(index));
     olePersistableBusinessObjectBase.getAlertBoList().add(alertBo);
   }
   return super.navigate(formBase, result, request, response);
 }
 /**
  * This method is to save alert
  *
  * @param formBase
  * @param result
  * @param request
  * @param response
  * @return ModelAndView
  */
 @RequestMapping(params = "methodToCall=saveAlert")
 public ModelAndView saveAlert(
     @ModelAttribute("KualiForm") DocumentFormBase formBase,
     BindingResult result,
     HttpServletRequest request,
     HttpServletResponse response) {
   MaintenanceDocumentForm maintenanceDocumentForm = (MaintenanceDocumentForm) formBase;
   OlePersistableBusinessObjectBase olePersistableBusinessObjectBase =
       (OlePersistableBusinessObjectBase)
           maintenanceDocumentForm.getDocument().getNewMaintainableObject().getDataObject();
   int index =
       Integer.parseInt(
           maintenanceDocumentForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
   olePersistableBusinessObjectBase.getAlertBoList().get(index).setEditFlag(false);
   AlertBo alertBo = olePersistableBusinessObjectBase.getAlertBoList().get(index);
   String status = null;
   if (alertBo.getAlertDate() != null) {
     Date alertDate = alertBo.getAlertDate();
     if (alertDate.toString().equals(new Date(System.currentTimeMillis()).toString())) {
       status = "Active";
     } else {
       int dateCompare = alertBo.getAlertDate().compareTo(new Date(System.currentTimeMillis()));
       if (dateCompare > 0) {
         status = "Future";
       } else if (dateCompare < 0) {
         status = "Complete";
       }
     }
   }
   alertBo.setStatus(status);
   return super.navigate(maintenanceDocumentForm, result, request, response);
 }
  @RequestMapping(params = "methodToCall=" + KRADConstants.Maintenance.METHOD_TO_CALL_EDIT)
  public ModelAndView maintenanceEdit(
      @ModelAttribute("KualiForm") MaintenanceDocumentForm form,
      BindingResult result,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    setupMaintenance(form, request, KRADConstants.MAINTENANCE_EDIT_ACTION);
    OlePersistableBusinessObjectBase olePersistableBusinessObjectBase =
        (OlePersistableBusinessObjectBase)
            form.getDocument().getNewMaintainableObject().getDataObject();
    olePersistableBusinessObjectBase.setAlertBoList(
        alertService.retrieveAlertList(form.getDocument().getDocumentNumber()));
    return getUIFModelAndView(form);
  }
 /**
  * This method is to delete alert
  *
  * @param formBase
  * @param result
  * @param request
  * @param response
  * @return ModelAndView
  */
 @RequestMapping(params = "methodToCall=deleteAlert")
 public ModelAndView deleteAlert(
     @ModelAttribute("KualiForm") DocumentFormBase formBase,
     BindingResult result,
     HttpServletRequest request,
     HttpServletResponse response) {
   MaintenanceDocumentForm maintenanceDocumentForm = (MaintenanceDocumentForm) formBase;
   OlePersistableBusinessObjectBase olePersistableBusinessObjectBase =
       (OlePersistableBusinessObjectBase)
           maintenanceDocumentForm.getDocument().getNewMaintainableObject().getDataObject();
   int index =
       Integer.parseInt(
           maintenanceDocumentForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
   if (olePersistableBusinessObjectBase.getAlertBoList().size() > index) {
     olePersistableBusinessObjectBase.getAlertBoList().remove(index);
   }
   return super.navigate(formBase, result, request, response);
 }
 /**
  * This method is to edit alert
  *
  * @param formBase
  * @param result
  * @param request
  * @param response
  * @return ModelAndView
  */
 @RequestMapping(params = "methodToCall=editAlert")
 public ModelAndView editAlert(
     @ModelAttribute("KualiForm") DocumentFormBase formBase,
     BindingResult result,
     HttpServletRequest request,
     HttpServletResponse response) {
   MaintenanceDocumentForm maintenanceDocumentForm = (MaintenanceDocumentForm) formBase;
   OlePersistableBusinessObjectBase olePersistableBusinessObjectBase =
       (OlePersistableBusinessObjectBase)
           maintenanceDocumentForm.getDocument().getNewMaintainableObject().getDataObject();
   int index =
       Integer.parseInt(
           maintenanceDocumentForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
   AlertBo alertBo = olePersistableBusinessObjectBase.getAlertBoList().get(index);
   alertBo.setEditFlag(true);
   alertBo.setAlertModifierId(GlobalVariables.getUserSession().getPrincipalId());
   alertBo.setAlertModifiedDate(new Date(System.currentTimeMillis()));
   alertBo.setAlertModifierName(
       alertService.getName(GlobalVariables.getUserSession().getPrincipalId()));
   return super.navigate(maintenanceDocumentForm, result, request, response);
 }
  @Override
  @RequestMapping(params = "methodToCall=docHandler")
  public ModelAndView docHandler(
      @ModelAttribute("KualiForm") DocumentFormBase formBase,
      BindingResult result,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // TODO getting double view if we call base, not sure how to handle
    // so pasting in superclass code
    // super.docHandler(formBase, request, response);
    // * begin copy/paste from the base
    MaintenanceDocumentForm form = (MaintenanceDocumentForm) formBase;

    // in all of the following cases we want to load the document
    if (ArrayUtils.contains(DOCUMENT_LOAD_COMMANDS, form.getCommand()) && form.getDocId() != null) {
      try {
        loadDocument(form);
        OlePersistableBusinessObjectBase olePersistableBusinessObjectBase =
            (OlePersistableBusinessObjectBase)
                form.getDocument().getNewMaintainableObject().getDataObject();
        olePersistableBusinessObjectBase.setAlertBoList(
            alertService.retrieveAlertList(form.getDocument().getDocumentNumber()));
      } catch (UnknownDocumentIdException udie) {
        ConfigurationService kualiConfigurationService =
            CoreApiServiceLocator.getKualiConfigurationService();
        StringBuffer sb = new StringBuffer();
        sb.append(kualiConfigurationService.getPropertyValueAsString(KRADConstants.KRAD_URL_KEY));
        sb.append(
            kualiConfigurationService.getPropertyValueAsString(
                KRADConstants.KRAD_INITIATED_DOCUMENT_URL_KEY));
        Properties props = new Properties();
        props.put(UifParameters.METHOD_TO_CALL, UifConstants.MethodToCallNames.START);
        GlobalVariables.getUifFormManager().removeSessionForm(form); // removeForm(form);
        return performRedirect(new InitiatedDocumentInfoForm(), sb.toString(), props);
      }
    } else if (KewApiConstants.INITIATE_COMMAND.equals(form.getCommand())) {
      createDocument(form);
    } else {
      LOG.error("docHandler called with invalid parameters");
      throw new IllegalArgumentException("docHandler called with invalid parameters");
    }
    // * end copy/paste from the base

    if (KewApiConstants.ACTIONLIST_COMMAND.equals(form.getCommand())
        || KewApiConstants.DOCSEARCH_COMMAND.equals(form.getCommand())
        || KewApiConstants.SUPERUSER_COMMAND.equals(form.getCommand())
        || KewApiConstants.HELPDESK_ACTIONLIST_COMMAND.equals(form.getCommand())
            && form.getDocId() != null) {
      // TODO: set state in view
      // form.setReadOnly(true);
      form.setMaintenanceAction(
          (form.getDocument()).getNewMaintainableObject().getMaintenanceAction());

      // Retrieving the FileName from BO table
      Maintainable tmpMaintainable = form.getDocument().getNewMaintainableObject();
      if (tmpMaintainable.getDataObject() instanceof PersistableAttachment) {
        PersistableAttachment bo =
            (PersistableAttachment)
                getBusinessObjectService()
                    .retrieve((PersistableBusinessObject) tmpMaintainable.getDataObject());
        if (bo != null) {
          request.setAttribute("fileName", bo.getFileName());
        }
      }
    } else if (KewApiConstants.INITIATE_COMMAND.equals(form.getCommand())) {
      // form.setReadOnly(false);
      setupMaintenance(form, request, KRADConstants.MAINTENANCE_NEW_ACTION);
    } else {
      LOG.error("We should never have gotten to here");
      throw new IllegalArgumentException("docHandler called with invalid parameters");
    }

    return getUIFModelAndView(form);
  }
  @RequestMapping(method = RequestMethod.POST, params = "methodToCall=addAlertLine")
  public ModelAndView addAlertLine(
      @ModelAttribute("KualiForm") DocumentFormBase formBase,
      BindingResult result,
      HttpServletRequest request,
      HttpServletResponse response) {
    String selectedCollectionPath =
        formBase.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
    if (StringUtils.isBlank(selectedCollectionPath)) {
      throw new RuntimeException(
          "Selected collection was not set for add line action, cannot add new line");
    }
    CollectionGroup collectionGroup =
        formBase.getPostedView().getViewIndex().getCollectionGroupByPath(selectedCollectionPath);
    String addLinePath = collectionGroup.getAddLineBindingInfo().getBindingPath();
    Object addLine = ObjectPropertyUtils.getPropertyValue(formBase, addLinePath);
    ModelAndView modelAndView = super.addLine(formBase, result, request, response);
    List<String> principalIds = new ArrayList<String>();
    MaintenanceDocumentForm maintenanceDocumentForm =
        (MaintenanceDocumentForm) modelAndView.getModel().get("KualiForm");
    OlePersistableBusinessObjectBase olePersistableBusinessObjectBase =
        (OlePersistableBusinessObjectBase)
            maintenanceDocumentForm.getDocument().getNewMaintainableObject().getDataObject();
    AlertBo alertBo = olePersistableBusinessObjectBase.getAlertBoList().get(0);
    olePersistableBusinessObjectBase.getAlertBoList().remove(0);
    if (StringUtils.isBlank(alertBo.getReceivingGroupId())
        && StringUtils.isBlank(alertBo.getReceivingUserId())
        && StringUtils.isBlank(alertBo.getReceivingRoleId())
        && StringUtils.isBlank(alertBo.getReceivingGroupId())
        && StringUtils.isEmpty(alertBo.getReceivingUserName())
        && StringUtils.isEmpty(alertBo.getReceivingRoleName())
        && StringUtils.isEmpty(alertBo.getReceivingGroupName())) {
      GlobalVariables.getMessageMap()
          .putErrorForSectionId("OLE-AlertSection", OLEConstants.SELECT_USER);
      return modelAndView;
    }
    alertBo.setAlertCreateDate(new Date(System.currentTimeMillis()));
    alertBo.setAlertInitiatorId(GlobalVariables.getUserSession().getPrincipalId());
    alertBo.setAlertInitiatorName(
        alertService.getName(GlobalVariables.getUserSession().getPrincipalId()));

    String status = null;
    if (alertBo.getAlertDate() != null) {
      Date alertDate = alertBo.getAlertDate();
      if (alertDate.toString().equals(new Date(System.currentTimeMillis()).toString())) {
        status = "Active";
      } else {
        int dateCompare = alertBo.getAlertDate().compareTo(new Date(System.currentTimeMillis()));
        if (dateCompare > 0) {
          status = "Future";
        } else if (dateCompare < 0) {
          status = "Complete";
        }
      }
    }
    alertBo.setStatus(status);
    alertBo.setAlertStatus(true);
    List<AlertBo> alerts = new ArrayList<AlertBo>();
    if (StringUtils.isNotBlank(alertBo.getReceivingUserId())
        && (alertBo.getReceivingUserName() == null
            || (alertBo.getReceivingUserName() != null
                && alertBo.getReceivingUserName().trim().isEmpty()))) {
      alertBo.setReceivingUserName(alertService.getName(alertBo.getReceivingUserId()));
    }
    if (StringUtils.isBlank(alertBo.getReceivingUserId())
        && (alertBo.getReceivingUserName() != null
            && !alertBo.getReceivingUserName().trim().isEmpty())) {
      alertBo.setReceivingUserId(alertService.getPersonId(alertBo.getReceivingUserName()));
    }
    if (StringUtils.isNotBlank(alertBo.getReceivingUserId())) {
      principalIds.add(alertBo.getReceivingUserId());
    }
    alerts.addAll(alertService.getAlertBo(alertBo, principalIds, false, false));
    principalIds = new ArrayList<String>();

    if (StringUtils.isNotBlank(alertBo.getReceivingGroupId())
        && (alertBo.getReceivingGroupName() == null
            || (alertBo.getReceivingGroupName() != null
                && alertBo.getReceivingGroupName().trim().isEmpty()))) {
      alertBo.setReceivingGroupName(alertService.getGroupName(alertBo.getReceivingGroupId()));
    }
    if (StringUtils.isBlank(alertBo.getReceivingGroupId())
        && (alertBo.getReceivingGroupName() != null
            && !alertBo.getReceivingGroupName().trim().isEmpty())) {
      alertBo.setReceivingGroupId(alertService.getGroupId((alertBo.getReceivingUserName())));
    }

    if (StringUtils.isNotBlank(alertBo.getReceivingGroupId())) {
      List<String> memberIds = groupService.getMemberPrincipalIds(alertBo.getReceivingGroupId());
      principalIds.addAll(memberIds);
    }
    alerts.addAll(alertService.getAlertBo(alertBo, principalIds, false, true));

    principalIds = new ArrayList<String>();

    if (StringUtils.isNotBlank(alertBo.getReceivingRoleId())
        && (alertBo.getReceivingRoleName() == null
            || (alertBo.getReceivingRoleName() != null
                && alertBo.getReceivingRoleName().trim().isEmpty()))) {
      alertBo.setReceivingRoleName(alertService.getRoleName(alertBo.getReceivingRoleId()));
    }
    if (StringUtils.isBlank(alertBo.getReceivingRoleId())
        && (alertBo.getReceivingRoleName() != null
            && !alertBo.getReceivingRoleName().trim().isEmpty())) {
      alertBo.setReceivingRoleId(alertService.getRoleId((alertBo.getReceivingRoleName())));
    }

    if (StringUtils.isNotBlank(alertBo.getReceivingRoleId())) {
      List<String> roleIds = new ArrayList<String>();
      roleIds.add(alertBo.getReceivingRoleId());
      Role role = roleService.getRole(alertBo.getReceivingRoleId());
      Collection collection =
          (Collection)
              roleService.getRoleMemberPrincipalIds(
                  role.getNamespaceCode(), role.getName(), new HashMap<String, String>());
      List<String> memberIds = new ArrayList<String>();
      memberIds.addAll(collection);
      principalIds.addAll(memberIds);
    }

    alerts.addAll(alertService.getAlertBo(alertBo, principalIds, true, false));

    olePersistableBusinessObjectBase.getAlertBoList().addAll(alerts);
    if (StringUtils.isBlank(alertBo.getReceivingUserId())
        && StringUtils.isNotBlank(alertBo.getReceivingGroupId())) {
      olePersistableBusinessObjectBase.getAlertBoList().remove(0);
    }
    if (StringUtils.isNotBlank(alertBo.getReceivingUserId())
        && StringUtils.isNotBlank(alertBo.getReceivingGroupId())) {
      alertBo.setReceivingGroupName(null);
      alertBo.setReceivingGroupId(null);
    }

    return modelAndView;
  }