/*
   * This view displays a list of all ItemTypes available.
   * If the parameter itemTypeName is set a new item type will be created.
   */
  public ModelAndView assoctypes(
      HttpServletRequest request, HttpServletResponse httpServletResponse) {
    ModelAndView mav = new ModelAndView("easyrec/assoctypes");

    Operator signedInOperator = Security.signedInOperator(request);
    RemoteTenant remoteTenant = viewInitializationService.initializeView(request, mav);

    String assocTypeName =
        ServletUtils.getSafeParameter(request, "assocTypeName", "").toUpperCase();

    if (signedInOperator != null) {

      if (!"".equals(assocTypeName)) {
        // create a new item type if the itemTypeName parameter is set

        String error = isValidAssocTypeName(assocTypeName);

        if ("".equals(error)) {
          tenantService.insertAssocTypeForTenant(remoteTenant.getId(), assocTypeName, true);
        } else {
          mav.addObject("error", error);
        }
      }

      mav.addObject("apiKey", signedInOperator.getApiKey());
      mav.addObject("assocTypes", assocTypeDAO.getTypes(remoteTenant.getId(), true));
      mav.addObject(
          "tenants", remoteTenantDAO.getTenantsFromOperator(remoteTenant.getOperatorId()));
    }

    return mav;
  }
  /*
  todo(pm): move function away from this controller
  */
  private RemoteTenant initializeView(HttpServletRequest request, ModelAndView mav) {
    RemoteTenant remoteTenant = null;

    String operatorId = ServletUtils.getSafeParameter(request, "operatorId", "");
    String tenantId = ServletUtils.getSafeParameter(request, "tenantId", "");

    String signedInOperatorId = Security.signedInOperatorId(request);
    Operator signedInOperator = Security.signedInOperator(request);

    if (signedInOperator != null) {
      if (Security.isDeveloper(request) && !Strings.isNullOrEmpty(operatorId))
        remoteTenant = remoteTenantDAO.get(operatorId, tenantId);
      else remoteTenant = remoteTenantDAO.get(signedInOperator.getOperatorId(), tenantId);

      if (remoteTenant != null) mav.addObject("remoteTenant", remoteTenant);
    }

    if (Security.isDeveloper(request) && !Strings.isNullOrEmpty(operatorId))
      mav.addObject("operatorId", operatorId);
    else mav.addObject("operatorId", signedInOperatorId);

    mav.addObject("tenantId", tenantId);
    mav.addObject("tenants", remoteTenantDAO.getTenantsFromOperator(operatorId));

    String apiKey = Operator.DEFAULT_API_KEY;

    if (signedInOperator != null) {
      apiKey = signedInOperator.getApiKey();
    }

    if (remoteTenant != null) {
      Set<String> itemTypes = itemTypeDAO.getTypes(remoteTenant.getId(), true);
      mav.addObject("availableItemTypes", itemTypes);

      Set<String> assocTypes = assocTypeDAO.getTypes(remoteTenant.getId(), true);
      assocTypes.add("");
      mav.addObject("availableAssocTypes", assocTypes);
    }

    mav.addObject("apiKey", apiKey);
    mav.addObject("signedIn", Security.isSignedIn(request));

    return remoteTenant;
  }
  private ModelAndView generateSearchResult(HttpServletRequest request, ModelAndView mav)
      throws ParseException {
    RemoteTenant tenant = initializeView(request, mav);

    // set to empty values so in case an error is returned the displayTag:table does not throw an
    // exception
    mav.addObject("itemSearchResult", null);
    mav.addObject("totalCount", 0);
    mav.addObject("pageSize", PAGE_SIZE);

    if (tenant == null) {
      logger.warn("no tenantId supplied");
      return mav;
    }

    String itemId = ServletUtils.getSafeParameter(request, "itemId", "");
    String description = ServletUtils.getSafeParameter(request, "description", "");
    String creationDateFrom = ServletUtils.getSafeParameter(request, "fromCreationDate", "");
    String creationDateTo = ServletUtils.getSafeParameter(request, "toCreationDate", "");
    String[] itemTypes = request.getParameterValues("itemTypes");
    boolean hasRules = ServletUtils.getSafeParameter(request, "hasRules", null) != null;
    String activatedString = ServletUtils.getSafeParameter(request, "isActivated", "null");
    String rulesOfType = ServletUtils.getSafeParameter(request, "rulesOfType", "");

    Boolean isActivated;
    if (activatedString.equalsIgnoreCase("null")) isActivated = null;
    else isActivated = activatedString.equalsIgnoreCase("true");

    mav.addObject("itemId", itemId);
    mav.addObject("description", description);
    mav.addObject("fromCreationDate", creationDateFrom);
    mav.addObject("toCreationDate", creationDateTo);
    mav.addObject("itemTypes", itemTypes);
    mav.addObject("hasRules", hasRules);
    mav.addObject("rulesOfType", rulesOfType);
    mav.addObject("isActivated", isActivated);

    ItemDAO.SortColumn sortColumn =
        tableSortParameterToDatabaseColumnName(
            ServletUtils.getSafeParameter(request, "d-16544-s", 0));
    Integer page = ServletUtils.getSafeParameter(request, "d-16544-p", 1);
    boolean sortDescending =
        ServletUtils.getSafeParameter(request, "d-16544-o", "0").equalsIgnoreCase("1");

    Date from = null;
    Date to = null;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(this.dateFormat);

    if (!Strings.isNullOrEmpty(creationDateFrom)) from = simpleDateFormat.parse(creationDateFrom);

    if (!Strings.isNullOrEmpty(creationDateTo)) to = simpleDateFormat.parse(creationDateTo);

    if (Strings.isNullOrEmpty(itemId)) itemId = null;

    if (Strings.isNullOrEmpty(description)) description = null;

    TimeConstraintVO creationDateConstraint =
        from != null || to != null ? new TimeConstraintVO(from, to) : null;
    Iterable<String> itemTypesIterable = itemTypes != null ? Arrays.asList(itemTypes) : null;

    List<Item> items =
        itemDAO.searchItems(
            tenant.getId(),
            itemId,
            itemTypesIterable,
            description,
            null,
            null,
            isActivated,
            creationDateConstraint,
            hasRules,
            rulesOfType,
            sortColumn,
            sortDescending,
            PAGE_SIZE * (page - 1),
            PAGE_SIZE);

    int totalCount =
        itemDAO.searchItemsTotalCount(
            tenant.getId(),
            itemId,
            itemTypesIterable,
            description,
            null,
            null,
            isActivated,
            creationDateConstraint,
            hasRules,
            rulesOfType);

    mav.addObject("itemSearchResult", items);
    mav.addObject("totalCount", totalCount);

    return mav;
  }