/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2019 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.axelor.apps.purchase.service.print;

import com.axelor.apps.ReportFactory;
import com.axelor.apps.base.service.app.AppBaseService;
import com.axelor.apps.purchase.db.PurchaseRequest;
import com.axelor.apps.purchase.exception.IExceptionMessage;
import com.axelor.apps.purchase.report.IReport;
import com.axelor.apps.report.engine.ReportSettings;
import com.axelor.apps.tool.ModelTool;
import com.axelor.apps.tool.ThrowConsumer;
import com.axelor.apps.tool.file.PdfTool;
import com.axelor.exception.AxelorException;
import com.axelor.exception.db.repo.TraceBackRepository;
import com.axelor.i18n.I18n;
import com.axelor.inject.Beans;
import java.io.File;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class PurchaseRequestPrintServiceImpl implements PurchaseRequestPrintService {

  @Override
  public String printPurchaseRequest(PurchaseRequest purchaseRequest, String formatPdf)
      throws AxelorException {

      String fileName = getPurchaseRequestFilesName(false, formatPdf);

    return PdfTool.getFileLinkFromPdfFile(print(purchaseRequest, formatPdf), fileName);
  }

  @Override
  public String printPurchaseRequests(List<Long> ids) throws IOException {
    List<File> printedPurchaseRequests = new ArrayList<>();
    ModelTool.apply(
        PurchaseRequest.class,
        ids,
        new ThrowConsumer<PurchaseRequest>() {

          @Override
          public void accept(PurchaseRequest purchaseRequest) throws Exception {
            printedPurchaseRequests.add(print(purchaseRequest, ReportSettings.FORMAT_PDF));
          }
        });
    String fileName = getPurchaseRequestFilesName(true, ReportSettings.FORMAT_PDF);
    return PdfTool.mergePdfToFileLink(printedPurchaseRequests, fileName);
  }

  public File print(PurchaseRequest purchaseRequest, String formatPdf) throws AxelorException {
    ReportSettings reportSettings = prepareReportSettings(purchaseRequest, formatPdf);
    return reportSettings.generate().getFile();
  }

  public ReportSettings prepareReportSettings(PurchaseRequest purchaseRequest, String formatPdf)
      throws AxelorException {
    if (purchaseRequest.getPrintingSettings() == null) {
      throw new AxelorException(
          TraceBackRepository.CATEGORY_MISSING_FIELD,
          String.format(
              I18n.get(IExceptionMessage.PURCHASE_REQUEST_MISSING_PRINTING_SETTINGS),
              purchaseRequest.getPurchaseRequestSeq()),
          purchaseRequest);
    }
    String locale = ReportSettings.getPrintingLocale(null);
    String title = getFileName(purchaseRequest);
    ReportSettings reportSetting =
        ReportFactory.createReport(IReport.PURCHASE_REQUEST, title + " - ${date}");


    return reportSetting
        .addParam("PurchaseRequestId", purchaseRequest.getId())
        .addParam("Locale", locale)
        .addParam("HeaderHeight", purchaseRequest.getPrintingSettings().getPdfHeaderHeight())
        .addParam("FooterHeight", purchaseRequest.getPrintingSettings().getPdfFooterHeight())
        .addFormat(formatPdf);
  }

  protected String getPurchaseRequestFilesName(boolean plural, String formatPdf) {
    return I18n.get(plural ? "Purchase requests" : "Purchase request")
        + " - "
        + Beans.get(AppBaseService.class).getTodayDate().format(DateTimeFormatter.BASIC_ISO_DATE)
        + "."
        + formatPdf;
  }

  @Override
  public String getFileName(PurchaseRequest purchaseRequest) {
    return I18n.get("Purchase request")
        + " "
        + purchaseRequest.getPurchaseRequestSeq();
  }
}
