/**
   * Handles the results pagination
   *
   * @author Coni
   * @param request
   * @param command
   * @return
   * @throws BusinessException
   */
  private ModelAndView handlePagination(
      HttpServletRequest request, ArrayList<String> errorMessages, Object command)
      throws BusinessException {
    logger.debug("handlePagination - START");

    ModelAndView mav = new ModelAndView(getSuccessView());
    SearchExchangeBean searchExchangeBean = (SearchExchangeBean) command;
    UserAuth userAuth =
        (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    try {
      if (request.getParameter(PAGE) != null) {
        if (NEXT.equals(request.getParameter(PAGE))) {
          searchExchangeBean.setCurrentPage(searchExchangeBean.getCurrentPage() + 1);
        }
        if (PREV.equals(request.getParameter(PAGE))) {
          searchExchangeBean.setCurrentPage(searchExchangeBean.getCurrentPage() - 1);
        }
        if (FIRST.equals(request.getParameter(PAGE))) {
          searchExchangeBean.setCurrentPage(1);
        }
        if (LAST.equals(request.getParameter(PAGE))) {
          searchExchangeBean.setCurrentPage(searchExchangeBean.getNbrOfPages());
        }
        if (NUMBER.equals(request.getParameter(PAGE))) {
          if (request.getParameter(PAGE_NBR) != null
              && !"".equals(request.getParameter(PAGE_NBR))) {
            searchExchangeBean.setCurrentPage(Integer.parseInt(request.getParameter(PAGE_NBR)));
          } else {
            // something is wrong
            // I will show the first page
            searchExchangeBean.setCurrentPage(-1);
          }
        }
      }
    } catch (Exception e) {
      // something is wrong
      // I will show the first page
      logger.error(PAGINATION_ERROR, e);
      searchExchangeBean.setCurrentPage(-1);
    }

    List<Exchange> res = null;
    try {

      res = BLExchange.getInstance().getResultsForSearch(searchExchangeBean, false);

      DecimalFormat dfReal = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
      dfReal.applyPattern("# ### ### ##0.0000");
      DecimalFormat dfInt = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
      dfInt.applyPattern("# ### ### ###");

      // set the exchange info panel header name
      for (Exchange exchange : res) {
        String headerName =
            exchange
                .getFirstCurrency()
                .getInitials()
                .concat(" - ")
                .concat(exchange.getSecondCurrency().getInitials());
        String panelHeaderName =
            ControllerUtils.getInstance().truncateName(headerName, NR_CHARS_PANEL_HEADER);
        exchange.setPanelHeaderName(panelHeaderName);
        if ((exchange.getRate() * 10) % 10 != 0) {
          exchange.setFormattedRate(dfReal.format(exchange.getRate()));
        } else {
          exchange.setFormattedRate(dfInt.format(exchange.getRate()));
        }
      }
      mav.addObject(SEARCH_RESULTS, res);
    } catch (BusinessException be) {
      logger.error(be.getMessage(), be);
      mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES);
      errorMessages.add(
          messageSource.getMessage(
              SEARCH_ERROR,
              new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()},
              RequestContextUtils.getLocale(request)));
    } catch (Exception e) {
      logger.error("", e);
      mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES);
      errorMessages.add(
          messageSource.getMessage(
              SEARCH_ERROR,
              new Object[] {ControllerUtils.getInstance().getFormattedCurrentTime()},
              RequestContextUtils.getLocale(request)));
    }

    mav.addObject(SEARCH_RESULTS, res);

    // find the number of pages shown in pagination area
    ControllerUtils.getInstance().findPagesLimit(searchExchangeBean, PAGES);

    mav.addObject(SEARCH_EXCHANGE_BEAN, searchExchangeBean);
    mav.addObject(COMMAND, command);

    logger.debug("handlePagination - END");
    return mav;
  }
  /**
   * Deletes exchanges
   *
   * @author coni
   * @param request
   * @param searchExchangeBean
   * @throws BusinessException
   * @throws ClassNotFoundException
   * @throws NoSuchMethodException
   * @throws SecurityException
   * @throws InvocationTargetException
   * @throws IllegalAccessException
   * @throws IllegalArgumentException
   */
  private void handleDeleteAllSimple(
      HttpServletRequest request,
      SearchExchangeBean searchExchangeBean,
      ArrayList<String> infoMessages,
      ArrayList<String> errorMessages)
      throws BusinessException, SecurityException, NoSuchMethodException, ClassNotFoundException,
          IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    logger.debug("handleDeleteAllSimple - START ");

    UserAuth userAuth =
        (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    Exchange exchange = null;

    for (int i = 0; i < searchExchangeBean.getExchangeId().length; i++) {
      logger.debug("Delete exchange : " + searchExchangeBean.getExchangeId()[i]);
      boolean isDeleted = true;

      try {
        exchange = BLExchange.getInstance().delete(searchExchangeBean.getExchangeId()[i]);
      } catch (BusinessException be) {
        logger.error("", be);
        errorMessages.add(
            messageSource.getMessage(
                DELETE_ERROR,
                new Object[] {
                  be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()
                },
                RequestContextUtils.getLocale(request)));
        isDeleted = false;
      }

      if (isDeleted) {
        // send notification
        String projectName = null;
        String message = null;
        Integer projectId = null;

        if (exchange != null) {
          if (exchange.getProjectDetail() != null) {
            Project project =
                BLProject.getInstance().get(exchange.getProjectDetail().getProjectId(), true);
            projectId = exchange.getProjectDetail().getProjectId();
            if (project != null) {
              projectName = project.getName();
            }
            message = IConstant.NOTIFICATION_MESSAGE_EXCHANGE_PROJECT_DELETE;
          } else {
            projectName = IConstant.KEY.concat(IConstant.FROM_ORGANIZATION);
            message = IConstant.NOTIFICATION_MESSAGE_EXCHANGE_ORG_DELETE;
          }
        }

        // send a notification regarding the deleting of the exchange
        sendNotificationExchangeDelete(
            projectId,
            exchange.getProjectDetailId(),
            userAuth.getOrganisationId(),
            message,
            new Object[] {
              exchange.getFirstCurrency().getName(),
              exchange.getSecondCurrency().getName(),
              projectName,
              userAuth.getFirstName().concat(" ").concat(userAuth.getLastName())
            },
            IConstant.NOTIFICATION_SUBJECT_EXCHANGE_DELETE,
            new Object[] {null},
            IConstant.NOTIFICATION_SETTING_EXCHANGE_DELETE);

        infoMessages.add(
            messageSource.getMessage(
                DELETE_SUCCESS,
                new Object[] {
                  exchange
                      .getFirstCurrency()
                      .getInitials()
                      .concat(" - ")
                      .concat(exchange.getSecondCurrency().getInitials())
                },
                RequestContextUtils.getLocale(request)));

        // add the new audit event only if the user is not AdminIT
        try {
          if (!userAuth.isAdminIT()) {
            if (exchange.getProjectDetailId() == null) {
              BLAudit.getInstance()
                  .add(
                      IConstant.AUDIT_EVENT_EXCHANGE_DELETE_TYPE,
                      userAuth.getFirstName(),
                      userAuth.getLastName(),
                      messageSource.getMessage(
                          IConstant.AUDIT_EVENT_EXCHANGE_FOR_ORG_DELETE_MESSAGE,
                          new Object[] {
                            exchange.getFirstCurrency().getName(),
                            exchange.getSecondCurrency().getName()
                          },
                          new Locale("en")),
                      messageSource.getMessage(
                          IConstant.AUDIT_EVENT_EXCHANGE_FOR_ORG_DELETE_MESSAGE,
                          new Object[] {
                            exchange.getFirstCurrency().getName(),
                            exchange.getSecondCurrency().getName()
                          },
                          new Locale("ro")),
                      ControllerUtils.getInstance().getOrganisationIdFromSession(request),
                      userAuth.getPersonId());
            } else {
              Project project = BLProject.getInstance().get(exchange.getProjectId(), true);
              BLAudit.getInstance()
                  .add(
                      IConstant.AUDIT_EVENT_EXCHANGE_DELETE_TYPE,
                      userAuth.getFirstName(),
                      userAuth.getLastName(),
                      messageSource.getMessage(
                          IConstant.AUDIT_EVENT_EXCHANGE_FOR_PROJECT_DELETE_MESSAGE,
                          new Object[] {
                            exchange.getFirstCurrency().getName(),
                            exchange.getSecondCurrency().getName(),
                            project.getName()
                          },
                          new Locale("en")),
                      messageSource.getMessage(
                          IConstant.AUDIT_EVENT_EXCHANGE_FOR_PROJECT_DELETE_MESSAGE,
                          new Object[] {
                            exchange.getFirstCurrency().getName(),
                            exchange.getSecondCurrency().getName(),
                            project.getName()
                          },
                          new Locale("ro")),
                      ControllerUtils.getInstance().getOrganisationIdFromSession(request),
                      userAuth.getPersonId());
            }
          }
        } catch (Exception exc) {
          logger.error("", exc);
        }
      }
    }
    logger.debug("handleDeleteAllSimple - END ");
  }
  /**
   * @author Coni Searches for exchanges
   * @param request
   * @param command
   * @param errorMessages
   * @param isDeleteAction
   * @return
   * @throws BusinessException
   */
  private ModelAndView handleSearch(
      HttpServletRequest request,
      Object command,
      ArrayList<String> errorMessages,
      boolean isDeleteAction)
      throws BusinessException {
    logger.debug("handeSearch - START");

    ModelAndView mav = new ModelAndView(getSuccessView());

    SearchExchangeBean searchExchangeBean = (SearchExchangeBean) command;

    List<Exchange> res = null;
    UserAuth userAuth =
        (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    DecimalFormat dfReal = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
    dfReal.applyPattern("# ### ### ##0.0000");
    DecimalFormat dfInt = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
    dfInt.applyPattern("# ### ### ###");

    try {
      res = BLExchange.getInstance().getResultsForSearch(searchExchangeBean, isDeleteAction);

      // set the exchange info panel header name
      for (Exchange exchange : res) {
        String headerName =
            exchange
                .getFirstCurrency()
                .getInitials()
                .concat(" - ")
                .concat(exchange.getSecondCurrency().getInitials());
        String panelHeaderName =
            ControllerUtils.getInstance().truncateName(headerName, NR_CHARS_PANEL_HEADER);
        exchange.setPanelHeaderName(panelHeaderName);
        if ((exchange.getRate() * 10) % 10 != 0) {
          exchange.setFormattedRate(dfReal.format(exchange.getRate()));
        } else {
          exchange.setFormattedRate(dfInt.format(exchange.getRate()));
        }
      }
      mav.addObject(SEARCH_RESULTS, res);
    } catch (BusinessException be) {
      logger.error(be.getMessage(), be);
      mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES);
      errorMessages.add(
          messageSource.getMessage(
              SEARCH_ERROR,
              new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()},
              RequestContextUtils.getLocale(request)));
    } catch (Exception e) {
      logger.error("", e);
      mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES);
      errorMessages.add(
          messageSource.getMessage(
              SEARCH_EXCEPTION_ERROR,
              new Object[] {ControllerUtils.getInstance().getFormattedCurrentTime()},
              RequestContextUtils.getLocale(request)));
    }

    // find the number of pages shown in pagination area
    ControllerUtils.getInstance().findPagesLimit(searchExchangeBean, PAGES);

    mav.addObject(SEARCH_EXCHANGE_BEAN, searchExchangeBean);
    mav.addObject(COMMAND, command);

    logger.debug("handleSearch - END - res.size=".concat(String.valueOf(res.size())));

    return mav;
  }