/**
  * Overrides the base implementation to add in new parameters to the return url
  *
  * <ul>
  *   <li>{@link KFSConstants.DISPATCH_REQUEST_PARAMETER}
  *   <li>{@link KFSConstants.BUSINESS_OBJECT_CLASS_ATTRIBUTE}
  *   <li>{@link KFSConstants.OVERRIDE_KEYS}
  * </ul>
  *
  * {@link KFSConstants.DISPATCH_REQUEST_PARAMETER}
  *
  * @see
  *     org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#getReturnUrl(org.kuali.rice.kns.bo.BusinessObject,
  *     java.util.Map, java.lang.String)
  */
 @Override
 public HtmlData getReturnUrl(
     BusinessObject businessObject,
     LookupForm lookupForm,
     List returnKeys,
     BusinessObjectRestrictions businessObjectRestrictions) {
   Properties parameters =
       getParameters(
           businessObject,
           lookupForm.getFieldConversions(),
           lookupForm.getLookupableImplServiceName(),
           returnKeys);
   parameters.put(
       KFSConstants.DISPATCH_REQUEST_PARAMETER, KFSConstants.MAINTENANCE_NEWWITHEXISTING_ACTION);
   parameters.put(
       KFSConstants.BUSINESS_OBJECT_CLASS_ATTRIBUTE, AccountDelegateGlobal.class.getName());
   parameters.put(
       KFSConstants.OVERRIDE_KEYS,
       "modelName"
           + KFSConstants.FIELD_CONVERSIONS_SEPERATOR
           + "modelChartOfAccountsCode"
           + KFSConstants.FIELD_CONVERSIONS_SEPERATOR
           + "modelOrganizationCode");
   setBackLocation(KFSConstants.MAINTENANCE_ACTION);
   return getReturnAnchorHtmlData(
       businessObject, parameters, lookupForm, returnKeys, businessObjectRestrictions);
 }
 /**
  * @see
  *     org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#performLookup(org.kuali.rice.kns.web.struts.form.LookupForm,
  *     java.util.Collection, boolean)
  */
 @Override
 public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) {
   lookupForm.setSuppressActions(false);
   lookupForm.setSupplementalActionsEnabled(true);
   lookupForm.setHideReturnLink(false);
   lookupForm.setShowMaintenanceLinks(true);
   return super.performLookup(lookupForm, resultTable, bounded);
 }
 @SuppressWarnings("unchecked")
 @Override
 public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) {
   String userName = (String) lookupForm.getFieldsForLookup().get("person.userName");
   if (StringUtils.isNotEmpty(userName)) {
     KcPerson person = getKcPersonService().getKcPersonByUserName(userName);
     if (person != null) {
       lookupForm.getFieldsForLookup().put("personId", person.getPersonId());
     }
   }
   return super.performLookup(lookupForm, resultTable, bounded);
 }
  /*
   * We want to allow users to query on principal name instead of person id,
   * so we need to translate before performing the lookup.
   */
  @SuppressWarnings("unchecked")
  @Override
  public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) {
    String userName = (String) lookupForm.getFieldsForLookup().get(USERNAME_FIELD);
    lookupForm.getFieldsForLookup().remove(FOR_INSTITUTIONAL_PROPOSAL);

    if (!StringUtils.isBlank(userName)) {
      KcPerson person = getKcPersonService().getKcPersonByUserName(userName);
      if (person != null) {
        lookupForm.getFieldsForLookup().put(PI_ID, person.getPersonId());
      }
      lookupForm.getFieldsForLookup().remove(USERNAME_FIELD);
    }
    List<ProposalLog> results =
        (List<ProposalLog>) super.performLookup(lookupForm, resultTable, bounded);
    if (StringUtils.containsIgnoreCase(lookupForm.getBackLocation(), NEGOTIATION_NEGOTIATION)) {
      return cleanSearchResultsForNegotiationLookup(results);
    } else {
      return results;
    }
  }
 /**
  * This is a hack. This is called by Lookup's execute and it's just our way of making sure that
  * maint links are turned on, even for an otherwise erstwhile non-maintainable object
  *
  * @see
  *     org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#applyConditionalLogicForFieldDisplay()
  */
 @Override
 public void applyConditionalLogicForFieldDisplay() {
   super.applyConditionalLogicForFieldDisplay();
   LookupForm lookupForm = (LookupForm) KNSGlobalVariables.getKualiForm();
   lookupForm.setShowMaintenanceLinks(true);
 }
  /**
   * This method performs the lookup and returns a collection of lookup items
   *
   * @param lookupForm
   * @param kualiLookupable
   * @param resultTable
   * @param bounded
   * @return
   */
  @Override
  public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) {
    Collection displayList;

    // call search method to get results
    if (bounded) {
      displayList = getSearchResults(lookupForm.getFieldsForLookup());
    } else {
      displayList = getSearchResultsUnbounded(lookupForm.getFieldsForLookup());
    }
    // MJM get resultTable populated here
    if (bounded) {
      HashMap<String, Class> propertyTypes = new HashMap<String, Class>();

      boolean hasReturnableRow = false;

      Person user = GlobalVariables.getUserSession().getPerson();

      try {
        // iterate through result list and wrap rows with return url and action urls
        for (Object aDisplayList : displayList) {
          BusinessObject element = (BusinessObject) aDisplayList;

          BusinessObjectRestrictions businessObjectRestrictions =
              getBusinessObjectAuthorizationService().getLookupResultRestrictions(element, user);
          String returnUrl = "www.bigfrickenRETURNurl";
          String actionUrls = "www.someACTIONurl";

          if (ObjectUtils.isNotNull(getColumns())) {
            List<Column> columns = getColumns();
            populateCutoffdateLabels();
            for (Object column : columns) {

              Column col = (Column) column;
              Formatter formatter = col.getFormatter();

              // pick off result column from result list, do formatting
              Object prop = ObjectUtils.getPropertyValue(element, col.getPropertyName());

              String propValue =
                  ObjectUtils.getFormattedPropertyValue(
                      element, col.getPropertyName(), col.getFormatter());
              Class propClass = getPropertyClass(element, col.getPropertyName());

              // formatters
              if (ObjectUtils.isNotNull(prop)) {
                // for Booleans, always use BooleanFormatter
                if (prop instanceof Boolean) {
                  formatter = new BooleanFormatter();
                }

                // for Dates, always use DateFormatter
                if (prop instanceof Date) {
                  formatter = new DateFormatter();
                }

                // for collection, use the list formatter if a formatter hasn't been defined yet
                if (prop instanceof Collection && ObjectUtils.isNull(formatter)) {
                  formatter = new CollectionFormatter();
                }

                if (ObjectUtils.isNotNull(formatter)) {
                  propValue = (String) formatter.format(prop);
                } else {
                  propValue = prop.toString();
                }
              }

              // comparator

              col.setComparator(
                  CellComparatorHelper.getAppropriateComparatorForPropertyClass(propClass));
              col.setValueComparator(
                  CellComparatorHelper.getAppropriateValueComparatorForPropertyClass(propClass));

              propValue =
                  super.maskValueIfNecessary(
                      element.getClass(),
                      col.getPropertyName(),
                      propValue,
                      businessObjectRestrictions);
              col.setPropertyValue(propValue);

              // add correct label for sysparam
              if (StringUtils.equals("unpaidBalance91toSYSPR", col.getPropertyName())) {
                col.setColumnTitle(cutoffdate91toSYSPRlabel);
              }
              if (StringUtils.equals("unpaidBalanceSYSPRplus1orMore", col.getPropertyName())) {
                col.setColumnTitle(cutoffdateSYSPRplus1orMorelabel);
              }
              if (StringUtils.equals("reportingName", col.getPropertyName())) {
                col.setColumnTitle(agencyShortName);
              }

              if (StringUtils.isNotBlank(propValue)) {
                // do not add link to the values in column "Customer Name"
                if (StringUtils.equals(customerNameLabel, col.getColumnTitle())) {
                  col.setPropertyURL(getCustomerLookupUrl(element, col.getColumnTitle()));
                } else if (StringUtils.equals(customerNumberLabel, col.getColumnTitle())) {
                  col.setPropertyURL(
                      getCustomerOpenInvoicesReportUrl(
                          element, col.getColumnTitle(), lookupForm.getFieldsForLookup()));
                } else if (StringUtils.equals(
                    ArConstants.ContractsGrantsAgingReportFields.TOTAL_CREDITS,
                    col.getColumnTitle())) {
                  col.setPropertyURL(getCreditMemoDocSearchUrl(element, col.getColumnTitle()));
                } else if (StringUtils.equals(
                    ArConstants.ContractsGrantsAgingReportFields.TOTAL_WRITEOFF,
                    col.getColumnTitle())) {
                  col.setPropertyURL(getCustomerWriteoffSearchUrl(element, col.getColumnTitle()));
                } else if (StringUtils.equals(
                    ArConstants.ContractsGrantsAgingReportFields.AGENCY_SHORT_NAME,
                    col.getColumnTitle())) {
                  col.setPropertyURL(getAgencyInquiryUrl(element, col.getColumnTitle()));
                } else {
                  col.setPropertyURL(
                      getCustomerOpenInvoicesReportUrl(
                          element, col.getColumnTitle(), lookupForm.getFieldsForLookup()));
                }
              }
            }

            ResultRow row = new ResultRow(columns, returnUrl, actionUrls);
            if (element instanceof PersistableBusinessObject) {
              row.setObjectId(((PersistableBusinessObject) element).getObjectId());
            }

            boolean rowReturnable = isResultReturnable(element);
            row.setRowReturnable(rowReturnable);
            if (rowReturnable) {
              hasReturnableRow = true;
            }

            resultTable.add(row);
          }

          lookupForm.setHasReturnableRow(hasReturnableRow);
        }
      } catch (Exception e) {
        // do nothing, try block needed to make CustomerAgingReportLookupableHelperServiceImpl-
        LOG.error(
            "problem during contractsGrantsAgingReportLookupableHelperService.performLookup()", e);
      }

      if (displayList.size() != 0) {
        ((ContractsGrantsAgingReportForm) lookupForm).setTotal0to30(total0to30.toString());
        ((ContractsGrantsAgingReportForm) lookupForm).setTotal31to60(total31to60.toString());
        ((ContractsGrantsAgingReportForm) lookupForm).setTotal61to90(total61to90.toString());
        ((ContractsGrantsAgingReportForm) lookupForm).setTotal91toSYSPR(total91toSYSPR.toString());
        ((ContractsGrantsAgingReportForm) lookupForm)
            .setTotalSYSPRplus1orMore(totalSYSPRplus1orMore.toString());
        ((ContractsGrantsAgingReportForm) lookupForm)
            .setTotalOpenInvoices(totalOpenInvoices.toString());
        ((ContractsGrantsAgingReportForm) lookupForm).setTotalCredits(totalCredits.toString());
        ((ContractsGrantsAgingReportForm) lookupForm).setTotalWriteOffs(totalWriteOffs.toString());
      }
    }
    return displayList;
  }
  /**
   * This method performs the lookup and returns a collection of lookup items
   *
   * @param lookupForm
   * @param lookupable
   * @param resultTable
   * @param bounded
   * @return KRAD Conversion: Lookupable performs customization of the search results.
   *     <p>Uses data dictionary for meta data.
   */
  @Override
  public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) {
    Collection<BusinessObject> displayList;

    // call search method to get results
    if (bounded) {
      displayList = (Collection<BusinessObject>) getSearchResults(lookupForm.getFieldsForLookup());
    } else {
      displayList =
          (Collection<BusinessObject>) getSearchResultsUnbounded(lookupForm.getFieldsForLookup());
    }

    List pkNames =
        getBusinessObjectMetaDataService().listPrimaryKeyFieldNames(getBusinessObjectClass());
    List returnKeys = getReturnKeys();
    Person user = GlobalVariables.getUserSession().getPerson();
    // iterate through result list and wrap rows with return url and action urls
    for (BusinessObject element : displayList) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Doing lookup for " + element.getClass());
      }
      BusinessObjectRestrictions businessObjectRestrictions =
          getBusinessObjectAuthorizationService().getLookupResultRestrictions(element, user);
      String returnUrl =
          getReturnUrl(element, lookupForm, returnKeys, businessObjectRestrictions)
              .constructCompleteHtmlTag();

      if (element instanceof PersistableBusinessObject) {
        if (element instanceof SegmentedBusinessObject) {
          if (LOG.isDebugEnabled()) {
            LOG.debug(
                "segmented property names "
                    + ((SegmentedBusinessObject) element).getSegmentedPropertyNames());
          }
          Collection<Column> columns = getColumns(element, businessObjectRestrictions);
          ResultRow row =
              new ResultRow(
                  (List<Column>) columns,
                  returnUrl,
                  getActionUrls(element, pkNames, businessObjectRestrictions));

          for (String propertyName :
              ((SegmentedBusinessObject) element).getSegmentedPropertyNames()) {
            columns.add(setupResultsColumn(element, propertyName, businessObjectRestrictions));
          }

          row.setObjectId(((PersistableBusinessObject) element).getObjectId());
          resultTable.add(row);
        } else {
          Collection<Column> columns = getColumns(element, businessObjectRestrictions);

          ResultRow row =
              new ResultRow(
                  (List<Column>) columns,
                  returnUrl,
                  getActionUrls(element, pkNames, businessObjectRestrictions));
          row.setObjectId(((PersistableBusinessObject) element).getObjectId());
          resultTable.add(row);
        }
      }
    }

    return displayList;
  }
  /**
   * This method performs the lookup and returns a collection of lookup items
   *
   * @param lookupForm
   * @param kualiLookupable
   * @param resultTable
   * @param bounded
   * @return
   */
  @Override
  public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) {
    Collection<BusinessObject> displayList;

    // Call search method to get results - always use unbounded to get the entire set of results.

    displayList =
        (Collection<BusinessObject>) getSearchResultsUnbounded(lookupForm.getFieldsForLookup());

    List pkNames =
        getBusinessObjectMetaDataService().listPrimaryKeyFieldNames(getBusinessObjectClass());
    List returnKeys = getReturnKeys();
    Person user = GlobalVariables.getUserSession().getPerson();

    // Iterate through result list and wrap rows with return url and action urls
    for (BusinessObject element : displayList) {
      LOG.debug("Doing lookup for " + element.getClass());

      ReferralToCollectionsLookupResult result = ((ReferralToCollectionsLookupResult) element);
      List<String> invoiceAttributesForDisplay = result.getInvoiceAttributesForDisplay();

      BusinessObjectRestrictions businessObjectRestrictions =
          getBusinessObjectAuthorizationService().getLookupResultRestrictions(result, user);
      // add list of awards to sub Result rows
      List<ResultRow> subResultRows = new ArrayList<ResultRow>();
      for (ContractsGrantsInvoiceDocument invoice : result.getInvoices()) {

        List<Column> subResultColumns = new ArrayList<Column>();
        InvoiceAccountDetail firstInvoiceAccountDetail = new InvoiceAccountDetail();

        // Set first invoice account detail
        if (CollectionUtils.isNotEmpty(invoice.getAccountDetails())) {
          firstInvoiceAccountDetail = invoice.getAccountDetails().get(0);
        }

        for (String propertyName : invoiceAttributesForDisplay) {
          if (propertyName.equalsIgnoreCase(KFSPropertyConstants.ACCOUNT_NUMBER)) {
            Account account =
                SpringContext.getBean(AccountService.class)
                    .getByPrimaryId(
                        firstInvoiceAccountDetail.getChartOfAccountsCode(),
                        firstInvoiceAccountDetail.getAccountNumber());
            subResultColumns.add(
                setupResultsColumn(account, propertyName, businessObjectRestrictions));
          } else {
            subResultColumns.add(
                setupResultsColumn(invoice, propertyName, businessObjectRestrictions));
          }
        }

        ResultRow subResultRow = new ResultRow(subResultColumns, "", "");
        subResultRow.setObjectId(((PersistableBusinessObjectBase) invoice).getObjectId());
        subResultRows.add(subResultRow);
      }

      // Create main customer header row
      Collection<Column> columns = getColumns(element, businessObjectRestrictions);
      HtmlData returnUrl =
          getReturnUrl(element, lookupForm, returnKeys, businessObjectRestrictions);
      ReferralToCollectionsResultRow row =
          new ReferralToCollectionsResultRow(
              (List<Column>) columns,
              subResultRows,
              returnUrl.constructCompleteHtmlTag(),
              getActionUrls(element, pkNames, businessObjectRestrictions));
      resultTable.add(row);
    }

    return displayList;
  }