/* BdfServer - Copyright (c) 2020-2023 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.synthesis;

import fr.exemole.bdfserver.api.BdfServer;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.fichotheque.Fichotheque;
import net.fichotheque.sphere.Sphere;
import net.mapeadores.opendocument.io.OdSource;
import net.mapeadores.opendocument.io.OdUtils;
import net.mapeadores.opendocument.io.OdZip;
import net.mapeadores.opendocument.io.OdZipEngine;
import net.mapeadores.opendocument.io.SheetNameChecker;
import net.mapeadores.opendocument.io.odtable.OdTableDefBuilder;
import net.mapeadores.opendocument.io.odtable.OdsOptions;
import net.mapeadores.opendocument.io.odtable.OdsXMLPart;
import net.mapeadores.opendocument.io.odtable.StyleManager;
import net.mapeadores.opendocument.io.odtable.StyleManagerBuilder;
import net.mapeadores.opendocument.io.odtable.TableSettings;
import net.mapeadores.util.io.TempStorageAppendable;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.localisation.MessageLocalisation;
import net.mapeadores.util.text.Label;
import net.mapeadores.util.xml.XMLUtils;
import net.mapeadores.util.xml.XMLWriter;


/**
 *
 * @author Vincent Calame
 */
public class SynthesisOds {

    private final Synthesis synthesis;
    private final SheetNameChecker sheetNameChecker;
    private final MessageLocalisation messageLocalisation;
    private final Lang lang;
    private final SphereSynthesis[] sphereSynthesisArray;
    private final BdfServer[] bdfServerArray;
    private final OdsOptions odsOptions;
    private final String summaryTableName;
    private final Map<String, String> sphereTableNameMap = new HashMap<String, String>();

    public SynthesisOds(Synthesis synthesis, OdsOptions odsOptions, Lang lang, MessageLocalisation messageLocalisation) {
        this.synthesis = synthesis;
        this.lang = lang;
        this.messageLocalisation = messageLocalisation;
        this.sphereSynthesisArray = synthesis.getSphereSynthesisArray();
        this.bdfServerArray = synthesis.getBdfServerArray();
        this.odsOptions = odsOptions;
        this.sheetNameChecker = new SheetNameChecker();
        this.summaryTableName = sheetNameChecker.checkName(messageLocalisation.toNotNullString("_ title.global.summary"));
        initSphereNameMap();
    }

    public void write(OutputStream outputStream) throws IOException {
        OdZipEngine.run(outputStream, OdZip.spreadSheet()
                .stylesOdSource((OdUtils.toStyleOdSource(odsOptions.elementMaps(), true)))
                .contentOdSource(new ContentOdSource())
                .settingsOdSource(OdUtils.getSettingsOdSource(getSettings()))
        );
    }

    private List<TableSettings> getSettings() {
        List<TableSettings> settingsList = new ArrayList<TableSettings>();
        settingsList.add(TableSettings.init(summaryTableName)
                .fixedColumns(2)
                .fixedRows(2)
        );
        for (SphereSynthesis sphereSynthesis : sphereSynthesisArray) {
            settingsList.add(TableSettings.init(getTableName(sphereSynthesis))
                    .fixedRows(2)
                    .fixedColumns(2)
            );
        }
        return settingsList;
    }

    private void initSphereNameMap() {
        for (SphereSynthesis sphereSynthesis : sphereSynthesisArray) {
            String sphereName = sphereSynthesis.getSphereName();
            String tableName;
            String sphereTitle = sphereSynthesis.getLabels().seekLabelString(lang, "");
            if (!sphereTitle.isEmpty()) {
                tableName = sphereName + " (" + sphereTitle + ")";
            } else {
                tableName = sphereName;
            }
            tableName = sheetNameChecker.checkName(tableName);
            sphereTableNameMap.put(sphereName, tableName);
        }
    }

    private String getTableName(SphereSynthesis sphereSynthesis) {
        return sphereTableNameMap.get(sphereSynthesis.getSphereName());
    }


    private class ContentOdSource implements OdSource {


        private ContentOdSource() {

        }

        @Override
        public void writeStream(OutputStream outputStream) throws IOException {
            StyleManager styleManager = initStyleManager();
            TempStorageAppendable bodyBuffer = new TempStorageAppendable();
            ContentXMLPart xmlPart = new ContentXMLPart(XMLUtils.toXMLWriter(bodyBuffer, 3), styleManager);
            xmlPart.writeSummaryTable();
            for (SphereSynthesis sphereSynthesis : sphereSynthesisArray) {
                xmlPart.writeSphereSynthesisTable(sphereSynthesis);
            }
            xmlPart.insertErrorLogTable(odsOptions.odLog(), "css log");
            OdUtils.writeSpreadSheetDocumentContent(outputStream, bodyBuffer, styleManager);
        }

        private StyleManager initStyleManager() {
            StyleManagerBuilder styleManagerBuilder = StyleManagerBuilder.init()
                    .setElementMaps(odsOptions.elementMaps());
            styleManagerBuilder.addTableDef(OdTableDefBuilder.init(summaryTableName)
                    .addStandard("FixedColumn")
                    .addStandard("FixedColumn")
                    .addStandards(sphereSynthesisArray.length)
                    .toOdTableDef()
            );
            for (SphereSynthesis sphereSynthesis : sphereSynthesisArray) {
                styleManagerBuilder.addTableDef(OdTableDefBuilder.init(getTableName(sphereSynthesis))
                        .addStandard("FixedColumn")
                        .addStandard("FixedColumn")
                        .addStandards(sphereSynthesis.getFichothequeSize())
                        .toOdTableDef()
                );
            }
            return styleManagerBuilder.toStyleManager();
        }

    }


    private class ContentXMLPart extends OdsXMLPart {

        private ContentXMLPart(XMLWriter xmlWriter, StyleManager styleManager) {
            super(xmlWriter, styleManager);
        }

        private void writeSummaryTable() throws IOException {
            tableStart(summaryTableName);
            rowStart();
            stringCell("", "Diagonal");
            stringCell(messageLocalisation.toNotNullString("_ title.global.sphere_collection"), "ColumnsLabel");
            for (SphereSynthesis sphereSynthesis : sphereSynthesisArray) {
                stringCell(sphereSynthesis.getSphereName(), "TopElementName");
            }
            rowEnd();
            rowStart();
            stringCell(messageLocalisation.toNotNullString("_ title.multi.fichotheques"), "RowsLabel");
            stringCell("", "Diagonal");
            for (SphereSynthesis sphereSynthesis : sphereSynthesisArray) {
                stringCell(sphereSynthesis.getLabels().seekLabelString(lang, ""), "TopElementTitle");
            }
            rowEnd();
            for (BdfServer bdfServer : bdfServerArray) {
                String fichothequeName = bdfServer.getName();
                rowStart();
                stringCell(fichothequeName, "ElementName");
                stringCell(getFichothequeTitle(bdfServer.getFichotheque()), "ElementTitle");
                for (SphereSynthesis sphereSynthesis : sphereSynthesisArray) {
                    Sphere sphere = sphereSynthesis.getSphere(fichothequeName);
                    if (sphere != null) {
                        SphereSynthesis.SpecificInfo specificInfo = sphereSynthesis.getSpecificInfo(fichothequeName);
                        String annotation = null;
                        if (specificInfo != null) {
                            annotation = getSpecificInfoText(specificInfo);
                        }
                        numberCell(String.valueOf(sphere.size()), "SphereName", 1, annotation);
                    } else {
                        stringCell("", "SphereName");
                    }

                }
                rowEnd();
            }
            tableEnd();
        }

        private void writeSphereSynthesisTable(SphereSynthesis sphereSynthesis) throws IOException {
            String[] fichothequeNameArray = sphereSynthesis.getFichothequeNameArray();
            tableStart(getTableName(sphereSynthesis));
            rowStart();
            stringCell("", "Diagonal");
            stringCell(messageLocalisation.toNotNullString("_ title.multi.fichotheques"), "ColumnsLabel");
            for (String fichothequeName : fichothequeNameArray) {
                stringCell(fichothequeName, "TopElementName");
            }
            rowEnd();
            rowStart();
            stringCell(messageLocalisation.toNotNullString("_ label.selection.users"), "RowsLabel");
            stringCell("", "Diagonal");
            for (String fichothequeName : fichothequeNameArray) {
                stringCell(getFichothequeTitle(fichothequeName), "TopElementTitle");
            }
            rowEnd();
            for (RedacteurSynthesis redacteurSynthesis : sphereSynthesis.getRedacteurSynthesisArray()) {
                rowStart();
                stringCell(redacteurSynthesis.getLogin(), "ElementName");
                stringCell(redacteurSynthesis.getCompleteName(), "ElementTitle", 1, getNameAnnotation(redacteurSynthesis));
                for (String fichothequeName : fichothequeNameArray) {
                    RedacteurSynthesis.FichothequeStatus status = redacteurSynthesis.getFichothequeStatus(fichothequeName);
                    if (status == null) {
                        stringCell("", "Status");
                    } else {
                        String annotation = null;
                        if (status.hasSpecificName()) {
                            annotation = getSpecificFichothequeStatusText(status);
                        }
                        addLevelCell(status.getLevel(), annotation);
                    }
                }
                rowEnd();
            }
            tableEnd();
        }

        private void addLevelCell(String level, String annotation) throws IOException {
            String style = null;
            switch (level) {
                case RedacteurSynthesis.A_ADMIN_LEVEL:
                    style = "Admin";
                    break;
                case RedacteurSynthesis.C_READONLY_LEVEL:
                    style = "Readonly";
                    break;
                case RedacteurSynthesis.D_INACTIVE_LEVEL:
                    style = "Inactive";
                    break;
                default:
                    style = "User";
            }
            stringCell(level, style, 1, annotation);
        }

    }

    private String getFichothequeTitle(String fichothequeName) {
        BdfServer bdfServer = synthesis.getBdfServer(fichothequeName);
        if (bdfServer != null) {
            return getFichothequeTitle(bdfServer.getFichotheque());
        } else {
            return "";
        }
    }

    private String getFichothequeTitle(Fichotheque fichotheque) {
        return fichotheque.getFichothequeMetadata().getTitleLabels().seekLabelString(lang, "");
    }

    private String getSpecificInfoText(SphereSynthesis.SpecificInfo specificInfo) {
        List<Label> labelList = specificInfo.getLabelList();
        StringBuilder buf = new StringBuilder();
        buf.append(messageLocalisation.toNotNullString("_ label.multi.specificphrases"));
        buf.append(messageLocalisation.toNotNullString("_ label.global.colon"));
        buf.append(" ");
        boolean next = false;
        for (Label label : labelList) {
            if (next) {
                buf.append(" / ");
            } else {
                next = true;
            }
            buf.append(label.getLabelString());
            buf.append(" (");
            buf.append(label.getLang().toString());
            buf.append(")");
        }
        return buf.toString();
    }

    private String getNameAnnotation(RedacteurSynthesis redacteurSynthesis) {
        List<String> otherNameList = redacteurSynthesis.getOtherNameList();
        if (otherNameList.isEmpty()) {
            return null;
        }
        String l10nKey;
        if (otherNameList.size() == 1) {
            l10nKey = "_ label.multi.specificname_one";
        } else {
            l10nKey = "_ label.multi.specificname_many";
        }
        StringBuilder buf = new StringBuilder();
        buf.append(messageLocalisation.toNotNullString(l10nKey));
        buf.append(messageLocalisation.toNotNullString("_ label.global.colon"));
        buf.append(" ");
        boolean next = false;
        for (String otherName : otherNameList) {
            if (next) {
                buf.append(" / ");
            } else {
                next = true;
            }
            buf.append(otherName);
        }
        return buf.toString();
    }

    private String getSpecificFichothequeStatusText(RedacteurSynthesis.FichothequeStatus fichothequeStatus) {
        StringBuilder buf = new StringBuilder();
        buf.append(messageLocalisation.toNotNullString("_ label.multi.specificname_one"));
        buf.append(messageLocalisation.toNotNullString("_ label.global.colon"));
        buf.append(" ");
        buf.append(fichothequeStatus.getSpecificName());
        return buf.toString();
    }

}
