/*
 * JasperReports - Free Java Reporting Library.
 * Copyright (C) 2001 - 2023 Cloud Software Group, Inc. All rights reserved.
 * http://www.jaspersoft.com
 *
 * Unless you have purchased a commercial license agreement from Jaspersoft,
 * the following license terms apply:
 *
 * This program is part of JasperReports.
 *
 * JasperReports is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JasperReports 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;

import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.oasis.JROdsExporter;
import net.sf.jasperreports.engine.export.oasis.JROdtExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.util.AbstractSampleApp;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleWriterExporterOutput;
import net.sf.jasperreports.export.SimpleXlsReportConfiguration;
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;
import net.sf.jasperreports.poi.export.JRXlsExporter;


/**
 * @author Teodor Danciu (teodord@users.sourceforge.net)
 */
public class FullApp extends AbstractSampleApp
{


	/**
	 *
	 */
	public static void main(String[] args) 
	{
		main(new FullApp(), args);
	}
	
	
	@Override
	public void test() throws JRException
	{
		compile();
		fill();
		pdf();
		html();
		try {
			mergeUsingITextWithFieldUpdate(
				Arrays.asList("target/reports/TableReport.pdf", "target/reports/PieChartReport.pdf"),
				"target/reports/Merged.pdf");
		}catch(IOException|DocumentException e) {
			System.err.println(e.toString());
		}
	}
	
	
	/**
	 *
	 */
	public void fill() throws JRException
	{
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("MaxOrderID", 12500);

		long start = System.currentTimeMillis();
		JasperFillManager.fillReportToFile("target/reports/TableReport.jasper", null, new JREmptyDataSource());
		JasperFillManager.fillReportToFile(
			"target/reports/PieChartReport.jasper",
			new HashMap<String, Object>(parameters), 
			getDemoHsqldbConnection());
		System.err.println("Filling time : " + (System.currentTimeMillis() - start));
	}
	
	
	
	/**
	 *
	 */
	public void pdf() throws JRException
	{
		long start = System.currentTimeMillis();
		JasperExportManager.exportReportToPdfFile("target/reports/TableReport.jrprint");
		JasperExportManager.exportReportToPdfFile("target/reports/PieChartReport.jrprint");
		System.err.println("PDF creation time : " + (System.currentTimeMillis() - start));
	}
	
	
	/**
	 *
	 */
	public void html() throws JRException
	{
		long start = System.currentTimeMillis();
		JasperExportManager.exportReportToHtmlFile("target/reports/TableReport.jrprint");
		JasperExportManager.exportReportToHtmlFile("target/reports/PieChartReport.jrprint");
		System.err.println("HTML creation time : " + (System.currentTimeMillis() - start));
	}
	
	
	void mergeUsingPDFBox(List<String> pdfFiles, String outputFile) throws IOException {
		PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
		pdfMergerUtility.setDestinationFileName(outputFile);
	
		pdfFiles.forEach(file -> {
			try {
				pdfMergerUtility.addSource(new File(file));
			} catch (FileNotFoundException e) {
				throw new RuntimeException(e);
			}
		});
	
		pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
	}	

	void mergeUsingIText(List<String> pdfFiles, String outputFile) throws IOException, DocumentException {
		List<PdfReader> pdfReaders = List.of(new PdfReader(pdfFiles.get(0)), new PdfReader(pdfFiles.get(1)));
		Document document = new Document();
		FileOutputStream fos = new FileOutputStream(outputFile);
		PdfWriter writer = PdfWriter.getInstance(document, fos);
		document.open();
		com.itextpdf.text.pdf.PdfContentByte directContent = writer.getDirectContent();
		PdfImportedPage pdfImportedPage;
		for (PdfReader pdfReader : pdfReaders) {
			int currentPdfReaderPage = 1;
			while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
				document.newPage();
				pdfImportedPage = writer.getImportedPage(pdfReader, currentPdfReaderPage);
				directContent.addTemplate(pdfImportedPage, 0, 0);
				currentPdfReaderPage++;
			}
		}
		
		fos.flush();
		document.close();
		fos.close();
	}

	void mergeUsingITextWithFieldUpdate(List<String> pdfFiles, String outputFile) throws IOException, DocumentException {
		List<PdfReader> pdfReaders = List.of(new PdfReader(pdfFiles.get(0)), new PdfReader(pdfFiles.get(1)));
		FileOutputStream out = new FileOutputStream(outputFile);
		Document document = new Document();
		PdfWriter writer = PdfWriter.getInstance(document, out);
		document.open();
		com.itextpdf.text.pdf.PdfContentByte directContent = writer.getDirectContent();
		// TODO: count page number instead of hardcode 100
		for(PdfReader reader: pdfReaders) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			PdfStamper stamper = new PdfStamper(reader, bos);
			AcroFields form = stamper.getAcroFields();

			for (Map.Entry<String, AcroFields.Item> entry : form.getFields().entrySet()) {
				System.err.println(entry.getKey());
				if(entry.getKey().equals("PAGENUM")) {
					form.setField(entry.getKey(), "100");
				}
			}
			stamper.setFormFlattening(true);
			stamper.close();

			int currentPdfReaderPage = 1;
			PdfReader newReader = new PdfReader(new ByteArrayInputStream(bos.toByteArray()));
			while (currentPdfReaderPage <= newReader.getNumberOfPages()) {
				document.newPage();
				PdfImportedPage pdfImportedPage = writer.getImportedPage(newReader, currentPdfReaderPage);
				directContent.addTemplate(pdfImportedPage, 0, 0);
				currentPdfReaderPage++;
			}
			out.flush();
		}
		document.close();
		out.close();
	}
}
