/* FichothequeLib_Tools - Copyright (c) 2024 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 net.fichotheque.tools.exportation.balayage.dom;

import java.text.ParseException;
import java.util.function.Consumer;
import net.fichotheque.Fichotheque;
import net.fichotheque.namespaces.BalayageSpace;
import net.fichotheque.selection.FicheQuery;
import net.fichotheque.tools.exportation.balayage.BalayageDefBuilder;
import net.fichotheque.tools.exportation.balayage.BalayagePostscriptumBuilder;
import net.fichotheque.tools.selection.SelectionDOMUtils;
import net.mapeadores.util.attr.AttributeBuilder;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.localisation.LangsUtils;
import net.mapeadores.util.logging.MessageHandler;
import net.mapeadores.util.text.RelativePath;
import net.mapeadores.util.text.StringUtils;
import net.mapeadores.util.xml.DOMUtils;
import net.mapeadores.util.xml.XMLUtils;
import org.w3c.dom.Element;


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

    private final Fichotheque fichotheque;
    private final BalayageDefBuilder balayageDefBuilder;
    private final BalayageUnitDOMReader balayageUnitDOMReader;
    private final MessageHandler messageHandler;

    public OldBalayageDOMReader(Fichotheque fichotheque, BalayageDefBuilder balayageDefBuilder, MessageHandler messageHandler) {
        this.fichotheque = fichotheque;
        this.balayageDefBuilder = balayageDefBuilder;
        this.messageHandler = messageHandler;
        this.balayageUnitDOMReader = new BalayageUnitDOMReader(fichotheque, balayageDefBuilder, messageHandler);
    }

    public OldBalayageDOMReader read(Element element) {
        DOMUtils.readChildren(element, new RootConsumer());
        return this;
    }

    public static OldBalayageDOMReader init(Fichotheque fichotheque, BalayageDefBuilder balayageDefBuilder, MessageHandler messageHandler) {
        return new OldBalayageDOMReader(fichotheque, balayageDefBuilder, messageHandler);
    }


    private class RootConsumer implements Consumer<Element> {

        private RootConsumer() {
        }

        @Override
        public void accept(Element element) {
            String tagName = element.getTagName();
            switch (tagName) {
                case "metadata":
                    readMetadata(element);
                    break;
                case "global-fiche-query":
                case "global-fiche-select":
                    FicheQuery ficheQuery = SelectionDOMUtils.getFicheConditionEntry(fichotheque, element).getFicheQuery();
                    if (!ficheQuery.isEmpty()) {
                        balayageDefBuilder.getSelectionOptionsBuilder().getCustomFichothequeQueriesBuilder().addFicheQuery(ficheQuery);
                    }
                    break;
                case "sitemap": {
                    AttributeBuilder attributeBuilder = balayageDefBuilder.getAttributesBuilder().getAttributeBuilder(BalayageSpace.SITEMAP_KEY);
                    String path = element.getAttribute("path");
                    if (!path.isEmpty()) {
                        attributeBuilder.addValue("path: " + path);
                    }
                    String fileName = element.getAttribute("file-name");
                    if (!fileName.isEmpty()) {
                        attributeBuilder.addValue("file-name: " + fileName);
                    }
                    String baseUrl = element.getAttribute("base-url");
                    if (!baseUrl.isEmpty()) {
                        attributeBuilder.addValue("base-url: " + baseUrl);
                    }
                    break;
                }
                case "postscriptum": {
                    DOMUtils.readChildren(element, new PostscriptumConsumer(balayageDefBuilder.getBalayagePostscriptumBuilder()));
                    break;
                }
                case "corpus-balayage":
                case "fiche-balayage":
                case "thesaurus-balayage":
                case "motcle-balayage":
                case "unique-balayage":
                case "document-balayage":
                case "illustration-balayage":
                    balayageUnitDOMReader.read(element);
                    break;
            }
        }

        private void readMetadata(Element element) {
            String root = element.getAttribute("root");
            if (root.length() > 0) {
                balayageDefBuilder.setTargetName(root);
            }
            String path = element.getAttribute("path");
            if (path.length() > 0) {
                try {
                    RelativePath relativePath = RelativePath.parse(path);
                    balayageDefBuilder.setTargetPath(relativePath);
                } catch (ParseException pe) {
                }
            }
            String langs = element.getAttribute("langs");
            if (langs.length() > 0) {
                Lang[] langArray = LangsUtils.toCleanLangArray(langs);
                for (Lang lang : langArray) {
                    balayageDefBuilder.addLang(lang);
                }
            }
            String defaultLangOption = element.getAttribute("default-lang-option");
            try {
                balayageDefBuilder.setDefaultLangOption(defaultLangOption);
            } catch (IllegalArgumentException iae) {
            }
            String param = element.getAttribute("transform");
            if (param.equals("false")) {
                balayageDefBuilder.setIgnoreTransformation(true);
            }
            String postCommand = element.getAttribute("post-command").trim();
            if (postCommand.length() > 0) {
                balayageDefBuilder.getBalayagePostscriptumBuilder().addExternalScript(postCommand);
            }
            DOMUtils.readChildren(element, new MetadataConsumer());
        }

    }


    private class MetadataConsumer implements Consumer<Element> {

        private MetadataConsumer() {
        }

        @Override
        public void accept(Element element) {
            String tagName = element.getTagName();
            switch (tagName) {
                case "mode":
                    String name = element.getAttribute("name");
                    try {
                        StringUtils.checkTechnicalName(name, true);
                        String limit = element.getAttribute("limit");
                        if (limit.length() > 0) {
                            if (limit.equals("date")) {
                                name = name + "|current";
                            }
                        }
                        balayageDefBuilder.getAttributesBuilder().appendValue(BalayageSpace.MODES_KEY, name);
                    } catch (java.text.ParseException pe) {
                    }
                    break;
            }
        }

    }


    private class PostscriptumConsumer implements Consumer<Element> {

        private final BalayagePostscriptumBuilder balayagePostscriptumBuilder;

        private PostscriptumConsumer(BalayagePostscriptumBuilder balayagePostscriptumBuilder) {
            this.balayagePostscriptumBuilder = balayagePostscriptumBuilder;
        }

        @Override
        public void accept(Element element) {
            String tagName = element.getTagName();
            switch (tagName) {
                case "script":
                case "command":
                    String command = XMLUtils.getData(element);
                    if (command.length() > 0) {
                        balayagePostscriptumBuilder.addExternalScript(command);
                    }
                    break;
                case "scrutari":
                    String scrutari = XMLUtils.getData(element);
                    if (scrutari.length() > 0) {
                        balayagePostscriptumBuilder.addScrutariExport(scrutari);
                    }
                    break;
                case "sql":
                    String sql = XMLUtils.getData(element);
                    if (sql.length() > 0) {
                        balayagePostscriptumBuilder.addSqlExport(sql);
                    }
                    break;
            }
        }

    }

}
