/*
 ************************************************************************************ 
 * Copyright (C) 2010-2011 Openbravo S.L.U. 
 * Licensed under the Openbravo Commercial License version 1.0 
 * You may obtain a copy of the License at http://www.openbravo.com/legal/obcl.html 
 * or in the legal folder of this module distribution.
 ************************************************************************************
 */
package org.openbravo.module.invoiceTaxReportEnhanced30.ad_reports;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperReport;

import org.hibernate.criterion.Restrictions;
import org.openbravo.base.filter.IsIDFilter;
import org.openbravo.base.secureApp.HttpSecureAppServlet;
import org.openbravo.base.secureApp.VariablesSecureApp;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBCriteria;
import org.openbravo.dal.service.OBDal;
import org.openbravo.data.FieldProvider;
import org.openbravo.erpCommon.ad_combos.OrganizationComboData;
import org.openbravo.erpCommon.businessUtility.Tree;
import org.openbravo.erpCommon.businessUtility.TreeData;
import org.openbravo.erpCommon.businessUtility.WindowTabs;
import org.openbravo.erpCommon.utility.ComboTableData;
import org.openbravo.erpCommon.utility.DateTimeData;
import org.openbravo.erpCommon.utility.FieldProviderFactory;
import org.openbravo.erpCommon.utility.JRFieldProviderDataSource;
import org.openbravo.erpCommon.utility.LeftTabsBar;
import org.openbravo.erpCommon.utility.NavigationBar;
import org.openbravo.erpCommon.utility.OBError;
import org.openbravo.erpCommon.utility.ToolBar;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.model.common.businesspartner.BusinessPartner;
import org.openbravo.model.common.enterprise.Organization;
import org.openbravo.module.invoiceTaxReportEnhanced30.api.MTRRecord;
import org.openbravo.module.invoiceTaxReportEnhanced30.comparators.OrderByTaxCategoryAndTaxName;
import org.openbravo.module.invoiceTaxReportEnhanced30.comparators.OrderByTaxPercentageAndBP;
import org.openbravo.module.invoiceTaxReportEnhanced30.comparators.OrderByTaxPercentageAndTaxId;
import org.openbravo.xmlEngine.XmlDocument;

public class OBMTR30_InvoiceTaxReportJR extends HttpSecureAppServlet {
  private static final long serialVersionUID = 1L;
  private OBMTR30InvoiceTaxReportDao dao;

  private List<MTRRecord> purchaseRecords;
  private List<MTRRecord> salesRecords;
  private FieldProvider[] detailDataPurchase_OrderByTaxNameAndBP;
  private FieldProvider[] dataPurchase_OrderByTaxCategoryAndTaxName;
  private FieldProvider[] dataPurchase_OrderByTaxPercentageAndBP;
  private FieldProvider[] dataSales_OrderByTaxNameAndBP;
  private FieldProvider[] dataSales_OrderByTaxCategoryAndTaxName;
  private FieldProvider[] detailDataSales_OrderByTaxPercentageAndBP;

  @Override
  public void doPost(final HttpServletRequest request, final HttpServletResponse response)
      throws IOException, ServletException {
    final VariablesSecureApp vars = new VariablesSecureApp(request);
    final String strUserCurrencyId = Utility.stringBaseCurrencyId(this, vars.getClient());
    String strCurrencyId = vars.getRequestGlobalVariable("inpCurrencyId",
        "OBMTR30_InvoiceTaxReportJR|currency");
    final String strDateFrom = vars.getRequestGlobalVariable("inpDateFrom",
        "OBMTR30_InvoiceTaxReportJR|DateFrom");
    final String strDateTo = vars.getRequestGlobalVariable("inpDateTo",
        "OBMTR30_InvoiceTaxReportJR|DateTo");
    String strOrg = vars.getRequestGlobalVariable("inpOrg", "OBMTR30_InvoiceTaxReportJR|Org");
    String strDetail = vars.getStringParameter("inpDetalle");
    String strSales = vars.getStringParameter("inpSales");
    final String strTaxId = vars.getStringParameter("inpTaxId");
    final String strWithholdingId = vars.getStringParameter("inpWithHoldingId");
    final String strTaxWithholding = vars.getStringParameter("inpWithHoldingId2");
    String strGroupby = vars.getStringParameter("inpGroupby");
    String strTaxType = vars.getStringParameter("inpTaxType", "OBMTR30_InvoiceTaxReportJR|taxtype");
    final String strBps = vars.getInStringParameter("inpcBPartnerId_IN", IsIDFilter.instance);
    String strBpName = vars.getStringParameter("inpBPNameId");
    if (strOrg.equals(""))
      strOrg = "0";

    String format = null;
    if (vars.commandIn("DEFAULT")) {
      strCurrencyId = vars.getGlobalVariable("inpCurrencyId",
          "OBMTR30_InvoiceTaxReportJR|currency", strUserCurrencyId);
      strSales = vars.getStringParameter("inpSales", "S");
      strDetail = vars.getStringParameter("inpDetalle", "-1");
      strGroupby = vars.getStringParameter("inpGroupby", "-1");
      strTaxType = vars.getStringParameter("inpTaxType", "V");
      printPageDataSheet(response, request, vars, strDateFrom, strDateTo, strOrg, strDetail,
          strSales, strCurrencyId, strGroupby, strTaxId, strWithholdingId, strTaxWithholding,
          strTaxType, strBpName);
    } else {
      if (vars.commandIn("PRINT_HTML")) {
        format = "html";
      } else if (vars.commandIn("PRINT_PDF")) {
        format = "pdf";
      } else if (vars.commandIn("RELATION_XLS")) {
        format = "xls";
      } else {
        pageError(response);
      }

      printPageData(response, request, vars, strDateFrom, strDateTo, strOrg, strDetail, strSales,
          format, strCurrencyId, strUserCurrencyId, strGroupby, strTaxId, strWithholdingId,
          strTaxWithholding, strTaxType, strBps, strBpName);
    }

  }

  private void printPageData(final HttpServletResponse response, final HttpServletRequest request,
      final VariablesSecureApp vars, final String strDateFrom, final String strDateTo,
      final String strOrg, final String strDetail, final String strSales, final String strOutput,
      final String strCurrencyId, final String strUserCurrencyId, final String strGroupby,
      final String strTaxId, final String strWithholdingId, final String strTaxWithholding,
      final String strTaxType, final String strBps, final String strBpName) throws IOException,
      ServletException {

    response.setContentType("text/html; charset=UTF-8");
    String strSale = "";
    String strPurchase = "";

    if (strDateFrom.equals("") && strDateTo.equals("") && strDetail.equals("-1")) {
      printPageDataSheet(response, request, vars, strDateFrom, strDateTo, strOrg, strDetail,
          strSales, strCurrencyId, strGroupby, strTaxId, strWithholdingId, strTaxWithholding,
          strTaxType, strBpName);

    }

    if (strSales.equals("S")) {
      strSale = Utility.messageBD(this, "OBMTR30_SALES_RECEIPTS", vars.getLanguage());
    } else if (strSales.equals("P")) {
      strPurchase = Utility.messageBD(this, "OBMTR30_PURCHASE_PAYMENTS", vars.getLanguage());
    } else {
      strSale = Utility.messageBD(this, "OBMTR30_SALES_RECEIPTS", vars.getLanguage());
      strPurchase = Utility.messageBD(this, "OBMTR30_PURCHASE_PAYMENTS", vars.getLanguage());
    }

    final String summary_TaxCategory = Utility.messageBD(this, "OBMTR30_SUMMARY_TAXCATEGORY",
        vars.getLanguage());
    final String summary_TaxPercentage = Utility.messageBD(this, "OBMTR30_SUMMARY_TAXPERCENTAGE",
        vars.getLanguage());
    final String totals = Utility.messageBD(this, "OBMTR30_TOTALS", vars.getLanguage());

    final HashMap<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("DETAIL", strDetail.equals("-1") ? "Y" : "N");
    parameters.put("cCountryId",
        new String(Utility.getContext(this, vars, "C_Country_Id", "OBMTR30_InvoiceTaxReportJR")));
    parameters.put("LANGUAGE", vars.getLanguage());
    parameters.put("SALE", strSale);
    parameters.put("PURCHASE", strPurchase);
    parameters.put("SUMMARY_TAXCATEGORY", summary_TaxCategory);
    parameters.put("SUMMARY_TAXPERCENTAGE", summary_TaxPercentage);
    parameters.put("TOTALS", totals);
    parameters.put("PARAM_ORG",
        Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg));
    parameters.put("PARAM_CURRENCY", strCurrencyId);
    parameters.put("PARAM_USERCURRENCY", strUserCurrencyId);
    parameters.put("cTaxId", strTaxId);
    parameters.put("cWithHoldingId", strWithholdingId);
    parameters.put("WithHoldingAsTaxId", strTaxWithholding);
    parameters.put("cTaxId", strTaxId);
    parameters.put("groupBy", strGroupby.equals("-1") ? "Y" : "N");
    parameters.put("isWithHolding", strTaxType.equals("W") ? "Y" : "N");
    parameters.put("isSOTRX", strSales);
    parameters.put("businessPartners", strBps);
    parameters.put("businessPartnersName", strBpName);
    try {
      OBContext.setAdminMode(true);
      parameters.put("organization", OBDal.getInstance().get(Organization.class, strOrg));
    } finally {
      OBContext.restorePreviousMode();
    }
    parameters.put("strDateFormat", vars.getJavaDateFormat());
    parameters.put("vars", vars);

    String strDateFormat;
    strDateFormat = vars.getJavaDateFormat();
    final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat);
    try {
      parameters.put("dateFrom", dateFormat.parse(strDateFrom));
      parameters.put("dateTo", dateFormat.parse(DateTimeData.nDaysAfter(this, strDateTo, "1")));
    } catch (final ParseException e) {
      log4j.error("Error while parsing dates in OBMTR30_InvoiceTaxReportJR: " + e);
      throw new ServletException(e.getMessage());
    }

    final JasperReport jasperDetailPurchase;
    final JasperReport jasperDetailSales;
    final JasperReport jasperSumPurchase;
    final JasperReport jasperSumSales;
    final JasperReport jasperSumPurchaseRate;
    final JasperReport jasperSumSalesRate;

    final String strLanguage = vars.getLanguage();
    final String strBaseDesign = getBaseDesignPath(strLanguage);
    dao = new OBMTR30InvoiceTaxReportDao(parameters);

    // Purchase, Sales, Both
    if ("P".equals(strSales)) {
      this.calculatePurchaseOperations(strGroupby);
      this.clearSalesOperations();
    } else if ("S".equals(strSales)) {
      this.calculateSalesOperations(strGroupby);
      this.clearPurchaseOperations();
    } else {
      // Purchase
      this.calculatePurchaseOperations(strGroupby);
      // Sales
      this.calculateSalesOperations(strGroupby);
    }

    final String strReportName = "@basedesign@/org/openbravo/module/invoiceTaxReportEnhanced30/ad_reports/OBMTR30_InvoiceTaxReport.jrxml";

    try {
      jasperDetailPurchase = Utility
          .getTranslatedJasperReport(
              this,
              strBaseDesign
                  + "/org/openbravo/module/invoiceTaxReportEnhanced30/ad_reports/OBMTR30_InvoiceTaxReportDetail.jrxml",
              vars.getLanguage(), strBaseDesign);
      jasperDetailSales = Utility
          .getTranslatedJasperReport(
              this,
              strBaseDesign
                  + "/org/openbravo/module/invoiceTaxReportEnhanced30/ad_reports/OBMTR30_InvoiceTaxReportDetail.jrxml",
              vars.getLanguage(), strBaseDesign);
      jasperSumPurchase = Utility
          .getTranslatedJasperReport(
              this,
              strBaseDesign
                  + "/org/openbravo/module/invoiceTaxReportEnhanced30/ad_reports/OBMTR30_InvoiceTaxReportSummary.jrxml",
              vars.getLanguage(), strBaseDesign);
      jasperSumSales = Utility
          .getTranslatedJasperReport(
              this,
              strBaseDesign
                  + "/org/openbravo/module/invoiceTaxReportEnhanced30/ad_reports/OBMTR30_InvoiceTaxReportSummary.jrxml",
              vars.getLanguage(), strBaseDesign);
      jasperSumPurchaseRate = Utility
          .getTranslatedJasperReport(
              this,
              strBaseDesign
                  + "/org/openbravo/module/invoiceTaxReportEnhanced30/ad_reports/OBMTR30_InvoiceTaxReportSummaryByRate.jrxml",
              vars.getLanguage(), strBaseDesign);
      jasperSumSalesRate = Utility
          .getTranslatedJasperReport(
              this,
              strBaseDesign
                  + "/org/openbravo/module/invoiceTaxReportEnhanced30/ad_reports/OBMTR30_InvoiceTaxReportSummaryByRate.jrxml",
              vars.getLanguage(), strBaseDesign);

    } catch (final JRException e) {
      log4j.error("Exception while getting translated Jasper Reports: " + e);
      throw new ServletException(e.getMessage());
    }
    
    Organization org = OBDal.getInstance().get(Organization.class,strOrg );
    
    parameters.put("PAR_DATETO",strDateTo);
    parameters.put("PAR_DATEFROM", strDateFrom);
    parameters.put("PAR_ORGNAME",org.getName());
    parameters.put("SR_DETAIL_PURCHASE", jasperDetailPurchase);
    parameters.put("SR_DETAIL_SALES", jasperDetailSales);
    parameters.put("SR_SUM_PURCHASE", jasperSumPurchase);
    parameters.put("SR_SUM_SALES", jasperSumSales);
    parameters.put("SR_SUM_PURCHASEBYRATE", jasperSumPurchaseRate);
    parameters.put("SR_SUM_SALESBYRATE", jasperSumSalesRate);
    parameters.put("dataSourceDetailPurchase", new JRFieldProviderDataSource(
        detailDataPurchase_OrderByTaxNameAndBP, vars.getJavaDateFormat()));
    parameters.put("dataSourceDetailSales", new JRFieldProviderDataSource(
        dataSales_OrderByTaxNameAndBP, vars.getJavaDateFormat()));
    parameters.put("dataSourceSumPurchase", new JRFieldProviderDataSource(
        dataPurchase_OrderByTaxCategoryAndTaxName, vars.getJavaDateFormat()));
    parameters.put("dataSourceSumSales", new JRFieldProviderDataSource(
        dataSales_OrderByTaxCategoryAndTaxName, vars.getJavaDateFormat()));
    parameters.put("dataSourceSumPurchaseByRate", new JRFieldProviderDataSource(
        dataPurchase_OrderByTaxPercentageAndBP, vars.getJavaDateFormat()));
    parameters.put("dataSourceSumSalesByRate", new JRFieldProviderDataSource(
        detailDataSales_OrderByTaxPercentageAndBP, vars.getJavaDateFormat()));

    renderJR(vars, response, strReportName, strOutput, parameters, null, null);

  }

  private void calculatePurchaseOperations(String strGroupBy) throws ServletException {
    purchaseRecords = new ArrayList<MTRRecord>(dao.mergeDataDetailPurchase());
    detailDataPurchase_OrderByTaxNameAndBP = FieldProviderFactory
        .getFieldProviderArray(purchaseRecords);

    Collections.sort(purchaseRecords, new OrderByTaxCategoryAndTaxName());
    dataPurchase_OrderByTaxCategoryAndTaxName = FieldProviderFactory
        .getFieldProviderArray(purchaseRecords);

    if ("-1".equals(strGroupBy)) {
      Collections.sort(purchaseRecords, new OrderByTaxPercentageAndBP());
    } else {
      Collections.sort(purchaseRecords, new OrderByTaxPercentageAndTaxId());
    }
    dataPurchase_OrderByTaxPercentageAndBP = FieldProviderFactory
        .getFieldProviderArray(purchaseRecords);

  }

  private void clearSalesOperations() {
    dataSales_OrderByTaxNameAndBP = null;
    dataSales_OrderByTaxCategoryAndTaxName = null;
    detailDataSales_OrderByTaxPercentageAndBP = null;
  }

  private void calculateSalesOperations(String strGroupBy) throws ServletException {
    salesRecords = new ArrayList<MTRRecord>(dao.mergeDataDetailSales());
    dataSales_OrderByTaxNameAndBP = FieldProviderFactory.getFieldProviderArray(salesRecords);

    Collections.sort(salesRecords, new OrderByTaxCategoryAndTaxName());
    dataSales_OrderByTaxCategoryAndTaxName = FieldProviderFactory
        .getFieldProviderArray(salesRecords);

    if ("-1".equals(strGroupBy)) {
      Collections.sort(salesRecords, new OrderByTaxPercentageAndBP());
    } else {
      Collections.sort(salesRecords, new OrderByTaxPercentageAndTaxId());
    }
    detailDataSales_OrderByTaxPercentageAndBP = FieldProviderFactory
        .getFieldProviderArray(salesRecords);
  }

  private void clearPurchaseOperations() {
    detailDataPurchase_OrderByTaxNameAndBP = null;
    dataPurchase_OrderByTaxCategoryAndTaxName = null;
    dataPurchase_OrderByTaxPercentageAndBP = null;
  }

  private void printPageDataSheet(final HttpServletResponse response,
      final HttpServletRequest request, final VariablesSecureApp vars, final String strDateFrom,
      final String strDateTo, final String strOrg, final String strDetail, final String strSales,
      final String strCurrencyId, final String strGroupby, final String strTaxId,
      final String strWithholdingId, final String strTaxWithholding, final String strTaxType,
      final String strBpName) throws IOException, ServletException {

    log4j.debug("Output: dataSheet");
    response.setContentType("text/html; charset=UTF-8");
    final PrintWriter out = response.getWriter();
    XmlDocument xmlDocument = null;

    final String strTitle = "FACTURAS CON EL EXTRANJERO";
    final String strSale = "";
    final String strPurchase = "";
    final String discard[] = { "discard", "discard", "discard", "discard" };
    log4j.debug("****** strSales: " + strSales + " fecha desde: " + strDateFrom + " fecha hasta: "
        + strDateTo + " detalle: " + strDetail);

    log4j.debug("****** xmlDocument");
    xmlDocument = xmlEngine.readXmlTemplate(
        "org/openbravo/module/invoiceTaxReportEnhanced30/ad_reports/OBMTR30_InvoiceTaxReport",
        discard).createXmlDocument();

    final ToolBar toolbar = new ToolBar(this, vars.getLanguage(), "OBMTR30_InvoiceTaxReportJR",
        false, "", "", "", false, "ad_reports", strReplaceWith, false, true);
    toolbar
        .prepareSimpleExcelToolBarTemplate("submitCommandForm('RELATION_XLS', false, null, 'OBMTR30_InvoiceTaxReport_Excel.xls', 'EXCEL');return false;");
    xmlDocument.setParameter("toolbar", toolbar.toString());

    try {
      final WindowTabs tabs = new WindowTabs(this, vars,
          "org.openbravo.module.invoiceTaxReportEnhanced30.ad_reports.OBMTR30_InvoiceTaxReportJR");
      xmlDocument.setParameter("parentTabContainer", tabs.parentTabs());
      xmlDocument.setParameter("mainTabContainer", tabs.mainTabs());
      xmlDocument.setParameter("childTabContainer", tabs.childTabs());
      xmlDocument.setParameter("theme", vars.getTheme());
      final NavigationBar nav = new NavigationBar(this, vars.getLanguage(),
          "OBMTR30_InvoiceTaxReport.html", classInfo.id, classInfo.type, strReplaceWith,
          tabs.breadcrumb());
      xmlDocument.setParameter("navigationBar", nav.toString());
      final LeftTabsBar lBar = new LeftTabsBar(this, vars.getLanguage(),
          "OBMTR30_InvoiceTaxReport.html", strReplaceWith);
      xmlDocument.setParameter("leftTabs", lBar.manualTemplate());
    } catch (final Exception ex) {
      throw new ServletException(ex);
    }
    {
      final OBError myMessage = vars.getMessage("OBMTR30_InvoiceTaxReportJR");
      vars.removeMessage("OBMTR30_InvoiceTaxReportJR");
      if (myMessage != null) {
        xmlDocument.setParameter("messageType", myMessage.getType());
        xmlDocument.setParameter("messageTitle", myMessage.getTitle());
        xmlDocument.setParameter("messageMessage", myMessage.getMessage());
      }
    }
    xmlDocument.setParameter("ccurrencyid", strCurrencyId);
    try {
      ComboTableData comboTableData = new ComboTableData(vars, this, "TABLEDIR", "C_Currency_ID",
          "", "",
          Utility.getContext(this, vars, "#AccessibleOrgTree", "OBMTR30_InvoiceTaxReportJR"),
          Utility.getContext(this, vars, "#User_Client", "OBMTR30_InvoiceTaxReportJR"), 0);
      Utility.fillSQLParameters(this, vars, null, comboTableData, "OBMTR30_InvoiceTaxReportJR",
          strCurrencyId);
      xmlDocument.setData("reportC_Currency_ID", "liststructure", comboTableData.select(false));
      comboTableData = null;
    } catch (final Exception ex) {
      throw new ServletException(ex);
    }
    xmlDocument.setParameter("ctaxid", strTaxId);

    try {
      ComboTableData comboTableData = new ComboTableData(vars, this, "TABLEDIR", "C_Tax_ID", "",
          "C_Tax - Not Parent or Withholding Tax", Utility.getContext(this, vars,
              "#AccessibleOrgTree", "OBMTR30_InvoiceTaxReportJR"), Utility.getContext(this, vars,
              "#User_Client", "OBMTR30_InvoiceTaxReportJR"), 0);
      Utility.fillSQLParameters(this, vars, null, comboTableData, "OBMTR30_InvoiceTaxReportJR",
          strTaxId);
      xmlDocument.setData("reportC_Tax_ID", "liststructure", comboTableData.select(false));
      comboTableData = null;
    } catch (final Exception ex) {
      throw new ServletException(ex);
    }
    xmlDocument.setParameter("cwithholdingid", strWithholdingId);

    try {

      ComboTableData comboTableData = new ComboTableData(vars, this, "TABLEDIR",
          "C_Withholding_ID", "", "", Utility.getContext(this, vars, "#AccessibleOrgTree",
              "OBMTR30_InvoiceTaxReportJR"), Utility.getContext(this, vars, "#User_Client",
              "OBMTR30_InvoiceTaxReportJR"), 0);
      Utility.fillSQLParameters(this, vars, null, comboTableData, "OBMTR30_InvoiceTaxReportJR",
          strTaxId);

      xmlDocument.setData("reportC_WithHolding_ID", "liststructure", comboTableData.select(false));
      comboTableData = null;
    } catch (final Exception ex) {
      throw new ServletException(ex);
    }
    xmlDocument.setParameter("cwithholdingid2", strTaxWithholding);

    try {

      ComboTableData comboTableData = new ComboTableData(vars, this, "TABLEDIR", "C_Tax_ID", "",
          "C_Tax Withholding", Utility.getContext(this, vars, "#AccessibleOrgTree",
              "OBMTR30_InvoiceTaxReportJR"), Utility.getContext(this, vars, "#User_Client",
              "OBMTR30_InvoiceTaxReportJR"), 0);
      Utility.fillSQLParameters(this, vars, null, comboTableData, "OBMTR30_InvoiceTaxReportJR",
          strTaxId);

      xmlDocument.setData("reportC_TaxWithHolding_ID", "liststructure",
          comboTableData.select(false));
      comboTableData = null;
    } catch (final Exception ex) {
      throw new ServletException(ex);
    }
    xmlDocument.setParameter("calendar", vars.getLanguage().substring(0, 2));
    xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
    xmlDocument.setParameter("paramLanguage", "defaultLang=\"" + vars.getLanguage() + "\";");
    xmlDocument.setParameter("dateFrom", strDateFrom);
    xmlDocument.setParameter("dateFromdisplayFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateFromsaveFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateTo", strDateTo);
    xmlDocument.setParameter("dateTodisplayFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateTosaveFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("detalle", strDetail);
    xmlDocument.setParameter("psale", strSales);
    xmlDocument.setParameter("ppurchase", strSales);
    xmlDocument.setParameter("pboth", strSales);
    xmlDocument.setParameter("adOrgId", strOrg);
    xmlDocument.setParameter("titleSale", strTitle);
    xmlDocument.setParameter("titlePurchase", strTitle);
    xmlDocument.setParameter("sale", strSale);
    xmlDocument.setParameter("purchase", strPurchase);
    xmlDocument.setParameter("groupby", strGroupby);
    xmlDocument.setParameter("ptax", strTaxType);
    xmlDocument.setParameter("inpBPNameId", strBpName);
    xmlDocument.setParameter("pwithholding", strTaxType);
    log4j.debug("****** setData reportAD_ORGID");

    xmlDocument.setData("reportAD_ORGID", "liststructure",
        OrganizationComboData.selectCombo(this, vars.getRole()));
    // +++++++++ MULTIBPSelector +++++++++++++++++++
    // put the selected business partners back in the select
    final String[] bps = getSelectedBPs(request);
    if (bps != null) {
      final StringBuilder sb = new StringBuilder();
      for (final String bpId : bps) {
        try {
          OBContext.setAdminMode(true);
          final BusinessPartner bp = OBDal.getInstance().get(BusinessPartner.class, bpId);
          sb.append("<option value='" + bpId + "'>" + bp.getIdentifier() + "</option>\n");
        } finally {
          OBContext.restorePreviousMode();
        }
      }
      xmlDocument.setParameter("sectionBusinessPartners", sb.toString());
    }
    // +++++++++ MULTIBPSelector +++++++++++++++++++
    out.println(xmlDocument.print());
    out.close();
  }

  // +++++++++ MULTIBPSelector +++++++++++++++++++
  private String[] getSelectedBPs(final HttpServletRequest request) {
    if (request.getParameter("bps") != null) {
      return request.getParameter("bps").split(",");
    }
    return request.getParameterValues("inpcBPartnerId_IN");
  }

  // +++++++++ MULTIBPSelector +++++++++++++++++++
  @Override
  public String getServletInfo() {
    return "Servlet OBMTR30_InvoiceTaxReport.";
  } // end of getServletInfo() method
}
