/*
 * 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.quality.service.print;

import com.axelor.apps.ReportFactory;
import com.axelor.apps.quality.db.ArtWork;
import com.axelor.apps.quality.exception.IExceptionMessage;
import com.axelor.apps.quality.report.IReport;
import com.axelor.apps.report.engine.ReportSettings;
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 java.io.File;
import java.time.LocalDate;

public class ArtWorkPrintServiceImpl {

  public String getFileName(ArtWork artWork) {

    return I18n.get("ArtWork") + " " + artWork.getRef();
  }

  public String printArtWork(ArtWork artWork, String format) throws AxelorException {

    String fileName = I18n.get("ArtWork") + " - " + LocalDate.now().toString() + "." + format;

    return PdfTool.getFileLinkFromPdfFile(print(artWork, format), fileName);
  }

  public File print(ArtWork artWork, String format) throws AxelorException {

    ReportSettings reportSettings = prepareReportSettings(artWork, format);

    return reportSettings.generate().getFile();
  }

  public ReportSettings prepareReportSettings(ArtWork artWork, String format)
      throws AxelorException {

    if (artWork.getPrintingSettings() == null) {
      throw new AxelorException(
          TraceBackRepository.CATEGORY_MISSING_FIELD,
          String.format(I18n.get(IExceptionMessage.QUALITY_CONTROL_MISSING_PRINTING_SETTINGS)),
          artWork);
    }

    String locale = ReportSettings.getPrintingLocale(artWork.getCompany().getPartner());
    String title = getFileName(artWork);

    ReportSettings reportSetting =
        ReportFactory.createReport(IReport.ART_WORK, title + " - ${date}");

    return reportSetting
        .addParam("artWorkId", artWork.getId())
        .addParam("Locale", locale)
        .addFormat(format);
  }
}
