package eu.eudat.logic.utilities.documents.word;

import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.UUID;

public class XWPFHtmlDocument extends POIXMLDocumentPart {

    private String html;
    private String id;

    public XWPFHtmlDocument(PackagePart pkg, String id) {
        super(pkg);
        this.html = "<!DOCTYPE html><html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"><style></style><title>HTML import</title></head><body><p></p></body>";
        this.id = id;
    }

    public String getHtml() {
        return html;
    }

    public void setHtml(String html) {
        this.html = this.html.replace("<p></p>", html);
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    protected void commit() throws IOException {
        PackagePart packagePart = getPackagePart();
        OutputStream outputStream = packagePart.getOutputStream();
        Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
        writer.write(html);
        writer.close();
        outputStream.close();
    }

    public static XWPFHtmlDocument addHtmlDocument(XWPFDocument document) throws InvalidFormatException {
        OPCPackage oPCPackage = document.getPackage();
        String id = UUID.randomUUID().toString();
        PackagePartName partName = PackagingURIHelper.createPartName("/word/" + id + ".html");
        PackagePart part = oPCPackage.createPart(partName, "text/html");
        XWPFHtmlDocument xWPFHtmlDocument = new XWPFHtmlDocument(part, id);
        document.addRelation(xWPFHtmlDocument.getId(), new XWPFHtmlRelation(), xWPFHtmlDocument);
        return xWPFHtmlDocument;
    }
}
