package com.knecon.fforesight.service.viewerdoc.service;

import java.io.File;
import java.util.Objects;
import java.util.Optional;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;

import com.pdftron.pdf.PDFDoc;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

@UtilityClass
public class ViewerDocVersioningUtility {

    public static final int currentVersion = 0;
    public static final String AUTHOR = "knecon technology GmbH";
    public static final String CUSTOM_DICT = "KNECON_VERSION";


    @SneakyThrows
    public void setVersionInDocument(PDFDoc pdfDoc) {

        pdfDoc.getDocInfo().setAuthor(AUTHOR);
        pdfDoc.getDocInfo().setKeywords(CUSTOM_DICT + ":" + currentVersion);
    }


    private static Optional<Integer> readVersionFromKeywords(String keywords) {

        String[] strings = keywords.split(":");
        if (strings.length != 2) {
            return Optional.empty();
        }
        if (!strings[0].equals(CUSTOM_DICT)) {
            return Optional.empty();
        }
        try {
            return Optional.of(Integer.parseInt(strings[1]));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }


    @SneakyThrows
    public boolean isCurrentVersion(File file) {

        try (PDDocument doc = Loader.loadPDF(file)) {
            return isCurrentVersion(doc.getDocumentInformation().getAuthor(), doc.getDocumentInformation().getKeywords());
        }
    }


    @SneakyThrows
    public boolean docIsCurrentVersion(PDFDoc pdfDoc) {

        return isCurrentVersion(pdfDoc.getDocInfo().getAuthor(), pdfDoc.getDocInfo().getKeywords());
    }


    private static boolean isCurrentVersion(String author, String keywords) {

        return Objects.equals(author, AUTHOR) //
               && readVersionFromKeywords(keywords).map(version -> version == currentVersion).orElse(false);
    }

}
