/* BdfServer - Copyright (c) 2021-2025 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.tools.exportation.transformation.defaulttemplates;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.configuration.PathConfiguration;
import fr.exemole.bdfserver.api.storage.TemplateStorage;
import fr.exemole.bdfserver.tools.exportation.table.BdfTableExportUtils;
import fr.exemole.bdfserver.tools.exportation.transformation.TransformationAvailabilities;
import fr.exemole.bdfserver.tools.exportation.transformation.compilers.TemplateCompilerUtils;
import fr.exemole.bdfserver.tools.storage.TemplateStorageUnitBuilder;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import net.fichotheque.SubsetKey;
import net.fichotheque.exportation.table.ColDef;
import net.fichotheque.exportation.table.SubsetTable;
import net.fichotheque.exportation.table.TableExport;
import net.fichotheque.exportation.transformation.TemplateDef;
import net.fichotheque.exportation.transformation.TemplateKey;
import net.fichotheque.namespaces.TransformationSpace;
import net.fichotheque.tools.exportation.transformation.TemplateDefBuilder;
import net.fichotheque.tools.permission.PermissionUtils;
import net.mapeadores.opendocument.css.output.StylesConversionEngine;
import net.mapeadores.opendocument.css.parse.LogCssErrorHandler;
import net.mapeadores.opendocument.elements.ElementMaps;
import net.mapeadores.opendocument.io.OdSource;
import net.mapeadores.opendocument.io.OdXML;
import net.mapeadores.opendocument.io.OdZip;
import net.mapeadores.opendocument.io.OdZipEngine;
import net.mapeadores.util.attr.Attributes;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.io.IOUtils;
import net.mapeadores.util.text.CleanedString;
import net.mapeadores.util.xml.AppendableXMLWriter;
import net.mapeadores.util.xml.XMLPart;
import net.mapeadores.util.xml.XMLUtils;
import net.mapeadores.util.xml.XMLWriter;


/**
 *
 * @author Vincent Calame
 */
class PropertiesOdtUnit {

    private PropertiesOdtUnit() {

    }

    static TemplateStorage.Unit build(BdfServer bdfServer, PathConfiguration pathConfiguration, TemplateKey templateKey, String tableExportName, Attributes initAttributes) {
        if (templateKey.isSimpleTemplate()) {
            throw new IllegalArgumentException("templateKey is simple template key");
        } else if (!templateKey.getExtension().equals("odt")) {
            throw new IllegalArgumentException("templateKey.getExtension != odt");
        }
        if (!TransformationAvailabilities.acceptPropertiesOdt(templateKey.getTransformationKey())) {
            throw new IllegalArgumentException("unsupported transformation key: " + templateKey.getTransformationKey());
        }
        TemplateDef templateDef = getTemplateDef(templateKey, tableExportName, initAttributes);
        byte[] templateOdt = getTemplateOdt(bdfServer, pathConfiguration, templateKey, tableExportName);
        return ((TemplateStorageUnitBuilder) TemplateStorageUnitBuilder.init("properties", templateDef)
                .addStorageContent("template.odt", templateOdt))
                .toTemplateStorageUnit();
    }

    static TemplateDef getTemplateDef(TemplateKey templateKey, String tableExportName, Attributes initAttributes) {
        TemplateDefBuilder builder = new TemplateDefBuilder(templateKey, initAttributes);
        CleanedString cleanedTableExportName = CleanedString.newInstance(tableExportName);
        if (cleanedTableExportName != null) {
            builder.getAttributesBuilder().appendValue(TransformationSpace.TABLEEXPORT_KEY, cleanedTableExportName);
        }
        return builder.toTemplateDef();
    }

    static byte[] getTemplateOdt(BdfServer bdfServer, PathConfiguration pathConfiguration, TemplateKey templateKey, String tableExportName) {
        SubsetKey corpusKey = templateKey.getTransformationKey().toCorpusKey();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            OdZipEngine.run(byteArrayOutputStream, OdZip.text()
                    .contentOdSource(new ContentOdSource(bdfServer, tableExportName, corpusKey))
                    .stylesOdSource(new StylesOdSource(bdfServer, pathConfiguration, templateKey)));
        } catch (IOException ioe) {
            throw new ShouldNotOccurException(ioe);
        }
        return byteArrayOutputStream.toByteArray();
    }


    private static class ContentOdSource implements OdSource {

        private final TableExport tableExport;
        private final SubsetKey corpusKey;
        private final String error;

        private ContentOdSource(BdfServer bdfServer, String tableExportName, SubsetKey corpusKey) {
            this.corpusKey = corpusKey;
            TableExport te;
            String err = null;
            if (!tableExportName.isEmpty()) {
                te = bdfServer.getTableExportManager().getTableExport(tableExportName);
                if (te == null) {
                    err = "Unknown tableExportName: " + tableExportName;
                }
            } else {
                te = BdfTableExportUtils.toDefaultTableExport(bdfServer, BdfTableExportUtils.ALL_FICHETABLEPARAMETERS, PermissionUtils.FICHOTHEQUEADMIN_PERMISSIONSUMMARY);
            }
            this.tableExport = te;
            this.error = err;
        }

        @Override
        public void writeStream(OutputStream outputStream) throws IOException {
            BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(buf);
            xmlWriter.appendXMLDeclaration();
            TemlateExampleXMLPart templateExampleXMLPart = new TemlateExampleXMLPart(xmlWriter);
            templateExampleXMLPart.start();
            if (tableExport != null) {
                SubsetTable subsetTable = tableExport.getSubsetTable(corpusKey);
                if (subsetTable != null) {
                    templateExampleXMLPart.writeFields(subsetTable);
                } else {
                    templateExampleXMLPart.writeError("Missing " + corpusKey + ".txt in table export");
                }
            } else {
                templateExampleXMLPart.writeError(error);
            }

            templateExampleXMLPart.end();
            buf.flush();
        }


        private class TemlateExampleXMLPart extends XMLPart {

            private TemlateExampleXMLPart(XMLWriter xmlWriter) {
                super(xmlWriter);
            }

            private void start() throws IOException {
                OdXML.openDocumentContent(this);
                OdXML.openBody(this);
                OdXML.openText(this);
            }

            private void writeError(String error) throws IOException {
                if (error != null) {
                    addSimpleElement("text:p", error);
                }
            }

            private void writeFields(SubsetTable subsetTable) throws IOException {
                for (ColDef colDef : subsetTable.getColDefList()) {
                    addSimpleElement("text:p", colDef.getColName() + " :");
                    openTag("text:p");
                    openTag("text:text-input", false);
                    addText(colDef.getColName());
                    closeTag("text:text-input", false);
                    closeTag("text:p", false);
                }
            }

            private void end() throws IOException {
                OdXML.closeText(this);
                OdXML.closeBody(this);
                OdXML.closeDocumentContent(this);
            }

        }

    }


    private static class StylesOdSource implements OdSource {

        private final BdfServer bdfServer;
        private final PathConfiguration pathConfiguration;
        private final TemplateKey templateKey;

        private StylesOdSource(BdfServer bdfServer, PathConfiguration pathConfiguration, TemplateKey templateKey) {
            this.bdfServer = bdfServer;
            this.pathConfiguration = pathConfiguration;
            this.templateKey = templateKey;
        }

        @Override
        public void writeStream(OutputStream outputStream) throws IOException {
            BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String stylesXml = DefaultTemplateUtils.getDefaultStylesXML(bdfServer);
            String stylesCss = "@import url(\"bdf://this/css/_ficheblockelements_odt.css\");";
            ElementMaps elementMaps = TemplateCompilerUtils.parseCss(bdfServer, pathConfiguration, stylesCss, TemplateCompilerUtils.getBaseURI(templateKey), "default_styles.css", new LogCssErrorHandler());
            String insertion = StylesConversionEngine.insertAllStyles(stylesXml, elementMaps, true);
            IOUtils.write(insertion, outputStream, "UTF-8");
        }

    }


}
