/**
   * This is called prior to displaying a form for the first time. It tells Spring the form/command
   * object to load into the request
   *
   * @see
   *     org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
   */
  protected Object formBackingObject(HttpServletRequest request) throws ServletException {

    Drug drug = null;

    if (Context.isAuthenticated()) {
      ConceptService cs = Context.getConceptService();
      String id = request.getParameter("drugId");
      if (id != null) {
        drug = cs.getDrug(Integer.valueOf(id));
      }
    }

    if (drug == null) drug = new Drug();

    return drug;
  }
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {

    ModelAndView mav = new ModelAndView();

    Drug drug = null;
    Location dftLoc = null;
    LocationService locationService = Context.getLocationService();

    String locationStr =
        Context.getAuthenticatedUser()
            .getUserProperties()
            .get(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION);

    try {
      dftLoc = locationService.getLocation(Integer.valueOf(locationStr));
    } catch (Exception e) {
      mav.addObject("msg", "pharmacymanagement.missingDftLoc");
    }
    @SuppressWarnings("unused")
    String pharmacyId = null;
    DrugLotDate dld = null;
    List<DrugLotDate> dlds = new ArrayList<DrugLotDate>();
    String patientIdStr = null;
    Patient patient = null;
    DrugOrderService service = Context.getService(DrugOrderService.class);
    List<Pharmacy> pharmacyList = service.getPharmacyByLocation(dftLoc);
    List<DrugOrder> drugOrders = new ArrayList<DrugOrder>();
    ConceptService conceptService = Context.getConceptService();
    Pharmacy pharmacy = null;

    List<DrugOrder> drugOrderList = new ArrayList<DrugOrder>();
    pharmacyId = pharmacyList.size() > 0 ? "not empty" : "";

    if (request.getParameter("patientId") != null
        && !request.getParameter("patientId").equals("")) {
      patientIdStr = request.getParameter("patientId");

      patient = Context.getPatientService().getPatient(Integer.valueOf(patientIdStr));
    }

    if (patient != null
        && request.getParameter("pharmacyId") != null
        && !request.getParameter("pharmacyId").equals("")) {

      drugOrders = Context.getOrderService().getDrugOrdersByPatient(patient);

      pharmacy = service.getPharmacyById(Integer.valueOf(request.getParameter("pharmacyId")));
      List<Integer> drugIdList = new ArrayList<Integer>();
      for (DrugOrder dor : drugOrders) {
        if (dor.getDiscontinued() == false) {
          drugOrderList.add(dor);
        }
      }

      Set<DrugProduct> lotNos = new HashSet<DrugProduct>();
      int solde = 0;

      List<Integer> drugIdss = new ArrayList<Integer>();
      List<DrugOrder> drugOrders1 = new ArrayList<DrugOrder>();
      for (DrugOrder drOr : drugOrderList) {
        if (!drugIdss.contains(drOr.getDrug().getDrugId()) && drOr.getAutoExpireDate() == null) {
          dld = new DrugLotDate();
          drugOrders1.add(drOr);
          drugIdList.add(drOr.getDrug().getDrugId());

          dld.setDrugOrder(drOr);
          drug = conceptService.getDrug(drOr.getDrug().getDrugId());
          dld.setDrug(drug);
          Map<String, String> dpMap = new HashMap<String, String>();
          lotNos =
              Utils.getLotsExpDp(
                  null, drOr.getDrug().getDrugId() + "", null, pharmacy.getPharmacyId() + "");

          /**
           * TO DO change this list of lotNos by the testLots in the Utils class remember to
           * retrieve a list of list instead of a unique set!!!!!!!!!!!!!!!!
           */
          if (lotNos.size() > 0) {
            for (DrugProduct drugproduct : lotNos) {
              if (drug != null)
                solde =
                    service.getCurrSoldeDisp(
                        drug.getDrugId() + "",
                        null,
                        pharmacy.getPharmacyId() + "",
                        drugproduct.getExpiryDate() + "",
                        drugproduct.getLotNo(),
                        null);

              if (solde != 0) {
                dpMap.put(
                    drugproduct.getLotNo()
                        + " / "
                        + solde
                        + " ("
                        + drugproduct.getExpiryDate()
                        + ") ",
                    drugproduct.getDrugproductId() + "");
                dld.setDpMap(dpMap);
              }
            }
            if (dpMap.size() > 0) dlds.add(dld);
          }
        }
        drugIdss.add(drOr.getDrug().getDrugId());
      }

      mav.addObject("patient", patient);
    }

    if (dlds.size() != 0) {
      mav.addObject("dlds", dlds);
    }

    List<Object[]> lots = null;
    DrugProduct drugproduct = null;
    if (request.getParameter("drugproductId") != null
        && !request.getParameter("drugproductId").equals("")) {
      drugproduct =
          service.getDrugProductById(Integer.valueOf(request.getParameter("drugproductId")));
      if (drugproduct != null) {
        if (drugproduct.getCmddrugId() != null) {
          if (drugproduct.getCmddrugId().getDestination().getLocationId()
              == dftLoc.getLocationId()) {
            if (drugproduct.getDrugId() != null)
              lots =
                  service.getLotNumbersExpirationDates(
                      drugproduct.getDrugId().getDrugId() + "",
                      null,
                      dftLoc.getLocationId() + "",
                      null);
            else
              lots =
                  service.getLotNumbersExpirationDates(
                      null,
                      drugproduct.getConceptId().getConceptId() + "",
                      dftLoc.getLocationId() + "",
                      null);
          }
        } else {
          if (service.getReturnStockByDP(drugproduct).get(0).getDestination().getLocationId()
              == dftLoc.getLocationId()) {
            if (drugproduct.getDrugId() != null)
              lots =
                  service.getLotNumbersExpirationDates(
                      drugproduct.getDrugId().getDrugId() + "",
                      null,
                      dftLoc.getLocationId() + "",
                      null);
            else
              lots =
                  service.getLotNumbersExpirationDates(
                      null,
                      drugproduct.getConceptId().getConceptId() + "",
                      dftLoc.getLocationId() + "",
                      null);
          }
        }
      }
      mav.addObject("lots", lots);
    }

    if (request.getParameter("dpFromGet") != null
        && !request.getParameter("dpFromGet").equals("")) {
      DrugProduct dp =
          service.getDrugProductById(Integer.valueOf(request.getParameter("dpFromGet")));
      String dateStr = dp.getExpiryDate().toString();
      String[] dateArr = dateStr.split("-");
      String date = dateArr[2] + "/" + dateArr[1] + "/" + dateArr[0];
      mav.addObject("date", date);
    }

    mav.setViewName(getViewName());
    return mav;
  }