/* (non-Javadoc)
   * @see gov.nih.nci.cadsr.cdecart.CdeCartUtilInterface#findCartNodes(javax.servlet.http.HttpSession, java.lang.String)
   */
  @Override
  public List<SearchNode> findCartNodes(HttpSession mySession, String principalName)
      throws Exception {

    String uid = principalName;

    // we shall be after login here, and uid is never null
    if (uid == null) {
      log.error("........No user found in session in findCartNodes");
      throw new AutheticationFailureException("Authenticated user not found in the session");
    }

    // we want to keep this cart in session not to retrieve it every time
    CDECart cdeCart = (CDECart) mySession.getAttribute(CaDSRConstants.CDE_CART);
    List<SearchNode> arr = null;

    try {
      if (cdeCart == null) {
        log.info("Object Cart is not found in session: " + principalName);
        cdeCart = findCdeCart(mySession, principalName);
      } else {
        log.info("Object Cart is found in session: " + principalName);
      }
      // We use either retrieved cart or found in the session cart to build the result for the
      // client page
      @SuppressWarnings("rawtypes")
      Collection col = cdeCart.getDataElements();

      arr = buildSearchNodeList(col);
      return arr;
    } catch (ObjectCartException oce) {
      log.error("Exception on cdeCart.getDataElements", oce);
      throw oce;
    }
  }
  /**
   * Delete items from the CDE Cart.
   *
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return
   * @throws IOException
   * @throws ServletException
   */
  public ActionForward removeItems(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException, ServletException {
    try {
      Collection items = new ArrayList();
      NCIUser user = (NCIUser) this.getSessionObject(request, CaDSRConstants.USER_KEY);
      CDECart sessionCart = (CDECart) this.getSessionObject(request, CaDSRConstants.CDE_CART);

      if (user != null) {
        return mapping.findForward("deleteSuccess");
      }
      CDECartFormBean myForm = (CDECartFormBean) form;
      String[] selectedDeleteItems = {};
      selectedDeleteItems = myForm.getSelectedItems();
      for (int i = 0; i < selectedDeleteItems.length; i++) {
        items.add(selectedDeleteItems[i]);
      }
      sessionCart.removeDataElements(items);
    } catch (Exception e) {
      if (log.isErrorEnabled()) {
        log.error("Exception on removeItems.....", e);
      }
      e.printStackTrace();
    }
    return mapping.findForward(SUCCESS);
  }
  /**
   * Displays CDE Cart.
   *
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return
   * @throws IOException
   * @throws ServletException
   */
  public ActionForward displayCDECart(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException, ServletException {

    try {
      NCIUser user = (NCIUser) this.getSessionObject(request, CaDSRConstants.USER_KEY);
      if (user != null) {
        return mapping.findForward("secureSuccess");
      }
      // Get the cart in the session
      CDECart sessionCart = (CDECart) this.getSessionObject(request, CaDSRConstants.CDE_CART);
      Collection<CDECartItem> cartItems = sessionCart.getDataElements();
      Collection<CDECartItem> items = new ArrayList<CDECartItem>();

      for (Object o : cartItems) {
        CDECartItem item = (CDECartItem) o;
        item.setPersistedInd(false);
        items.add(item);
      }
      sessionCart.mergeDataElements(items);

      this.setSessionObject(request, CaDSRConstants.CDE_CART, sessionCart);
    } catch (Exception exp) {
      if (log.isErrorEnabled()) {
        log.error("Exception on displayCDECart.....", exp);
      }
      exp.printStackTrace();
    }
    return mapping.findForward(SUCCESS);
  }
  /* (non-Javadoc)
   * @see gov.nih.nci.cadsr.cdecart.CdeCartUtilInterface#deleteCartNodes(javax.servlet.http.HttpSession, java.lang.String, java.lang.String[])
   */
  @Override
  public void deleteCartNodes(
      final HttpSession mySession, final String principalName, final String[] ids)
      throws Exception {
    if ((ids == null) || (ids.length == 0)) {
      log.warn("Nothing to delete no ID received");
      return;
    }

    if (mySession == null) {
      // this shall never happen; controller provides the session
      log.warn("Session is not found");
      return;
    }

    // we shall be after login here, and principalName is never null
    if (principalName == null) {
      log.error("........No user found in session in findCartNodes");
      throw new AutheticationFailureException("Authenticated user not found in the session");
    }
    try {
      if (ocURL == null) { // try to get it again for a chance fixed in DB
        ToolOptionsModel cdeCartOptionsModel =
            toolOptionsDAO.getToolOptionsByToolNameAndProperty("ObjectCartAPI", "URL");
        if (cdeCartOptionsModel != null) {
          ocURL = cdeCartOptionsModel.getValue();
        }
        if (ocURL == null) {
          log.warn("Cannot get a value of ObjectCart URL from the system configuration");
        }
      }

      ObjectCartClient ocClient = null;

      if (!ocURL.equals("")) ocClient = new ObjectCartClient(ocURL);
      else ocClient = new ObjectCartClient();

      // Get the cart in the session
      CDECart sessionCart = (CDECart) mySession.getAttribute(CaDSRConstants.CDE_CART);

      CDECart userCart = new CDECartOCImpl(ocClient, principalName, CaDSRConstants.CDE_CART);

      Collection<String> items = Arrays.asList(ids);

      sessionCart.removeDataElements(items);
      userCart.removeDataElements(items);
    } catch (ObjectCartException oce) {
      log.error("Exception on cdeCart.getDataElements", oce);
      throw oce;
    }
  }
  /* (non-Javadoc)
   * @see gov.nih.nci.cadsr.cdecart.CdeCartUtilInterface#addToCart(javax.servlet.http.HttpSession, java.lang.String, java.util.List)
   */
  @Override
  public void addToCart(HttpSession mySession, String principalName, List<String> cdeIds)
      throws ObjectCartException, AutheticationFailureException {
    if ((cdeIds == null) || (mySession == null)) {
      log.debug("Nothing to save");
      return;
    }

    CDECart sessionCart = (CDECart) mySession.getAttribute(CaDSRConstants.CDE_CART);

    if (sessionCart == null) {
      sessionCart = findCdeCart(mySession, principalName);
    }

    String userName = principalName;

    // we shall be after login here, and userName is never null
    if (userName == null) {
      log.error("........No user found in session in addToCart");
      throw new AutheticationFailureException("Authenticated user not found in the session");
    }

    try {
      if (ocURL == null) { // try to get it again for a chance fixed in DB
        ToolOptionsModel cdeCartOptionsModel =
            toolOptionsDAO.getToolOptionsByToolNameAndProperty("ObjectCartAPI", "URL");
        if (cdeCartOptionsModel != null) {
          ocURL = cdeCartOptionsModel.getValue();
        }
        if (ocURL == null) {
          log.warn("Cannot get a value of ObjectCart URL from the system configuration");
        }
      }

      ObjectCartClient ocClient = null;

      if (!ocURL.equals("")) ocClient = new ObjectCartClient(ocURL);
      else ocClient = new ObjectCartClient();

      CDECart userCart = new CDECartOCImpl(ocClient, userName, CaDSRConstants.CDE_CART);

      List<DataElementModel> deModelList = dataElementDAO.getCdeByDeIdseqList(cdeIds);

      Collection<DataElementTransferObject> addCandidates = buildCartTransferObjects(deModelList);
      Collection<CDECartItem> items = new ArrayList<CDECartItem>();

      for (DataElementTransferObject deto : addCandidates) {
        CDECartItem cartItem = sessionCart.findDataElement(deto.getIdseq());
        if (cartItem == null) {
          CDECartItem cdeItem = new CDECartItemTransferObject();
          cdeItem.setPersistedInd(false); // we have IDs only for items to save
          cdeItem.setItem(deto);
          items.add(cdeItem);
        } else {
          cartItem.setPersistedInd(true);
          items.add(cartItem);
        }
      }

      userCart.mergeDataElements(items);
    } catch (ObjectCartException oce) {
      log.error("Exception on cdeCart.getDataElements", oce);
      throw oce;
    }
  }