package tourplaner.business;

import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import tourplaner.object.Log;
import tourplaner.object.Tour;

import com.itextpdf.text.pdf.PdfWriter;

import java.awt.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

/**
 * PDF Report generierung mit iText
 *
 * Erstellt Reports über einzelne Touren und fasst alle Touren zusammen
 *
 * iText 4 ist gratis verfügbar, siehe:
 * https://github.com/ymasory/iText-4.2.0
 */
public class Reporter {

    private static final Font catFont = new Font(Font.TIMES_ROMAN, 18,
            Font.BOLD);
    private static final Font subFont = new Font(Font.TIMES_ROMAN, 16,
            Font.BOLD);

    /**
     * Erstellt den Summary Report
     */
    public static void sumReport(){
        ArrayList<Tour> tours = TourPlaner.getAllTours();
        String file = ConfigHelper.getIniString(ConfigHelper.getStandartConfig(), "report", "path") + "summary.pdf";
        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            addMetaData(document, new Tour("Summary", "String dauer", "String mapJson", 1, "String start", "String ziel"));
            addSumRepo(document, tours);

            document.close();
        } catch (DocumentException | FileNotFoundException e) {
            LogHelper.error(e.getMessage(), e.getClass().getName());
        }
        if(ConfigHelper.getIniInt(ConfigHelper.getStandartConfig(), "settings", "openpdf") == 1) {
            FileHelper.openDefault(file);
        }
    }

    /**
     * Content des Sumary reports
     * @param document Document auf das geschrieben wird
     * @param touren Touren die berechnet werden
     * @throws DocumentException Fehler beim schreiben auf das Dokument
     */
    private static void addSumRepo(Document document, ArrayList<Tour> touren) throws DocumentException {
        double dauer = 0;
        double strecke = 0;
        double calDauer = 0;
        double calStecke = 0;
        for (Tour tour:touren) {
            calStecke += tour.getStrecke();
            calDauer += Double.parseDouble(tour.getDauer());
            ArrayList<Log> logs = tour.getLogs();
            for (Log log:logs) {
                dauer += log.getDauer();
                strecke += log.getStrecke();
            }
        }
        Anchor anchor = new Anchor(ConfigHelper.getLangIniString("rsummrepo"), catFont);
        anchor.setName(ConfigHelper.getLangIniString("rsummrepo"));
        // Second parameter is the number of the chapter
        Chapter catPart = new Chapter(new Paragraph(anchor), 1);
        Paragraph subPara = new Paragraph(ConfigHelper.getLangIniString("rdaten"), subFont);
        Section subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph(ConfigHelper.getLangIniString("reportvon") + " " + System.getProperty("user.name") + ", " + new Date()));
        subCatPart.add(new Paragraph(EinheitenAdder.addMinuten(ConfigHelper.getLangIniString("rzeitallerlogs") + " " + dauer)));
        subCatPart.add(new Paragraph(EinheitenAdder.addKm(ConfigHelper.getLangIniString("rstreckeallerlogs") + " " + strecke)));
        subCatPart.add(new Paragraph(EinheitenAdder.addMinuten(ConfigHelper.getLangIniString("rcalzeitallerlogs") + " " + calDauer)));
        subCatPart.add(new Paragraph(EinheitenAdder.addKm(ConfigHelper.getLangIniString("calstreckeallerloggs") + " " + calStecke)));
        document.add(catPart);
    }

    /**
     * Erstellt einen Tour Report
     * @param tourname Name der Tour die Gereportet werden soll
     */
    public static void createTourReport(String tourname)   {
        Tour tour = TourPlaner.getTour(tourname);
        tour.setLog(TourPlaner.getLogs(tourname));
        String file = ConfigHelper.getIniString(ConfigHelper.getStandartConfig(), "report", "path") + tourname+".pdf";
        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            addMetaData(document, tour);
//            addTitlePage(document, tour);
            addContent(document, tour);
            document.close();
        } catch (DocumentException | FileNotFoundException e) {
            LogHelper.error(e.getMessage(), e.getClass().getName());
        }
        if(ConfigHelper.getIniInt(ConfigHelper.getStandartConfig(), "settings", "openpdf") == 1) {
            FileHelper.openDefault(file);
        }
    }

    // iText allows to add metadata to the PDF which can be viewed in your Adobe
    // Reader
    // under File -> Properties
    private static void addMetaData(Document document, Tour tour) {
        document.addTitle(ConfigHelper.getLangIniString("tourreportvon") + " " + tour.getName());
        document.addSubject(ConfigHelper.getLangIniString("tourplanervon"));
        document.addKeywords(ConfigHelper.getLangIniString("reportkeywords"));
        document.addAuthor(ConfigHelper.getLangIniString("tourplaner"));
        document.addCreator(ConfigHelper.getLangIniString("tourplaner"));
    }

    /**
     * Erstellt den inhalt des Reports
     * @param document Aktuelles Dokument
     * @param tour Aktuelle Tour
     * @throws DocumentException Fehler beim hinzufügen des Inhaltes
     */
    private static void addContent(Document document, Tour tour) throws DocumentException {
        Anchor anchor = new Anchor(ConfigHelper.getLangIniString("tourreportvon") + tour.getName(), catFont);
        anchor.setName(ConfigHelper.getLangIniString("tourreportvon") + tour.getName());

        // Second parameter is the number of the chapter
        Chapter catPart = new Chapter(new Paragraph(anchor), 1);

        Paragraph subPara = new Paragraph(ConfigHelper.getLangIniString("tour"), subFont);
        Section subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph(ConfigHelper.getLangIniString("reportvon") + " " + System.getProperty("user.name") + ", " + new Date()));
        subCatPart.add(new Paragraph(ConfigHelper.getLangIniString("reportstart") + " " + tour.getStart()));
        subCatPart.add(new Paragraph(ConfigHelper.getLangIniString("reportziel") + " " + tour.getZiel()));
        subCatPart.add(new Paragraph(EinheitenAdder.addMinuten(ConfigHelper.getLangIniString("reportdauercal") + " " + tour.getDauer())));
        subCatPart.add(new Paragraph(EinheitenAdder.addKm(ConfigHelper.getLangIniString("reportstreckecal") + " " + tour.getStrecke())));
        Paragraph emptyLine = new Paragraph();
        addEmptyLine(emptyLine, 5);
        subCatPart.add(emptyLine);
        // now add all this to the document
        document.add(catPart);

        Image image1 = null;
        try {
            image1 = Image.getInstance(TourPlaner.getImagePdfPath(tour.getName()));
            image1.setAlignment(Element.ALIGN_CENTER);
            image1.scaleAbsolute(600, 400);

            document.add(image1);
        } catch (IOException e) {
            LogHelper.error(e);
        }
        ArrayList<Log> logs = tour.getLogs();
        // Second parameter is the number of the chapter
        anchor = new Anchor(ConfigHelper.getLangIniString("logs"), catFont);
        anchor.setName(ConfigHelper.getLangIniString("logs"));
        catPart = new Chapter(new Paragraph(anchor), 2);
        catPart.add(new Paragraph(ConfigHelper.getLangIniString("countlog") + " " + logs.size()));

        for (Log log: logs) {
            subPara = new Paragraph(ConfigHelper.getLangIniString("logvom") + " " + log.getDatum() , subFont);
            subCatPart = catPart.addSection(subPara);
            subCatPart.add(new Paragraph(EinheitenAdder.addMinuten(ConfigHelper.getLangIniString("logdauer") + " " + log.getDauer())));
            subCatPart.add(new Paragraph(EinheitenAdder.addMinuten(ConfigHelper.getLangIniString("logpause") + " " + log.getPause())));
            subCatPart.add(new Paragraph(EinheitenAdder.addMinuten(ConfigHelper.getLangIniString("loggegangen") + " " + log.getGegangen())));
            subCatPart.add(new Paragraph(EinheitenAdder.addSpeed(ConfigHelper.getLangIniString("logavg") + " " + log.getAvgspeed())));
            subCatPart.add(new Paragraph(EinheitenAdder.addKm(ConfigHelper.getLangIniString("logstrecke") + " " + log.getStrecke())));
            subCatPart.add(new Paragraph(EinheitenAdder.addMeter(ConfigHelper.getLangIniString("loghight") + " " + log.getHightmeter())));
            subCatPart.add(new Paragraph(ConfigHelper.getLangIniString("logbemerkung") + " " + log.getBemerkung()));
            subCatPart.add(new Paragraph( "Rating " + log.getRating()));
        }
        // now add all this to the document
        document.add(catPart);
    }

    /**
     * Fügt eine leere zeile an den Paragraph an
     * @param paragraph Hier wird hinzugefügt
     * @param number Um wie viele Leere Zeilen hinzugefügt werden soll
     */
    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }
}
