/* BdfServer - Copyright (c) 2013-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.importation.engines;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.externalsource.ExternalSourceUtils;
import java.text.ParseException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import net.fichotheque.ExistingIdException;
import net.fichotheque.FichothequeEditor;
import net.fichotheque.Subset;
import net.fichotheque.SubsetItem;
import net.fichotheque.externalsource.ExternalSource;
import net.fichotheque.importation.TiesImport;
import net.fichotheque.include.IncludeKey;
import net.fichotheque.permission.PermissionSummary;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.thesaurus.Thesaurus;
import net.fichotheque.thesaurus.ThesaurusEditor;
import net.fichotheque.thesaurus.policies.DynamicEditPolicy;
import net.fichotheque.tools.junction.JunctionChangeEngine;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.text.Label;
import net.fichotheque.junction.JunctionEditor;


/**
 *
 * @author Vincent Calame
 */
final class TiesImportEngine {

    private final JunctionEditor junctionEditor;
    private final FichothequeEditor fichothequeEditor;
    private final SubsetItem mainSubsetItem;
    private final BdfServer bdfServer;
    private final Predicate<Subset> subsetAccessPredicate;


    private TiesImportEngine(BdfServer bdfServer, JunctionEditor junctionEditor, SubsetItem mainSubsetItem, PermissionSummary permissionSummary) {
        this.junctionEditor = junctionEditor;
        this.fichothequeEditor = junctionEditor.getFichothequeEditor();
        this.mainSubsetItem = mainSubsetItem;
        this.bdfServer = bdfServer;
        this.subsetAccessPredicate = permissionSummary.getSubsetAccessPredicate();
    }

    static void run(BdfServer bdfServer, JunctionEditor junctionEditor, SubsetItem mainSubsetItem, TiesImport tiesImport, PermissionSummary permissionSummary) {
        TiesImportEngine tiesImportEngine = new TiesImportEngine(bdfServer, junctionEditor, mainSubsetItem, permissionSummary);
        tiesImportEngine.runReplace(tiesImport);
        tiesImportEngine.runAppend(tiesImport);
    }

    private void runReplace(TiesImport tiesImport) {
        List<IncludeKey> removedIncludeKeyList = tiesImport.getRemovedIncludeKeyList();
        List<TiesImport.TieImport> replaceList = tiesImport.getReplaceTieImportList();
        if ((removedIncludeKeyList.isEmpty()) && (replaceList.isEmpty())) {
            return;
        }
        Set<IncludeKey> clearExisting = new LinkedHashSet<IncludeKey>();
        clearExisting.addAll(removedIncludeKeyList);
        for (TiesImport.TieImport tieImport : replaceList) {
            if (subsetAccessPredicate.test(tieImport.getOtherSubset())) {
                clearExisting.add(tieImport.getIncludeKey());
            }
        }
        JunctionChangeEngine replaceEngine = JunctionChangeEngine.clearExistingEngine(mainSubsetItem, clearExisting);
        for (TiesImport.TieImport tieImport : replaceList) {
            if (subsetAccessPredicate.test(tieImport.getOtherSubset())) {
                addTie(replaceEngine, tieImport);
            }
        }
        junctionEditor.updateJunctions(mainSubsetItem, replaceEngine.toJunctionChanges());
    }

    private void runAppend(TiesImport tiesImport) {
        List<TiesImport.TieImport> appendList = tiesImport.getAppendTieImportList();
        if (appendList.isEmpty()) {
            return;
        }
        JunctionChangeEngine appendEngine = JunctionChangeEngine.appendEngine(mainSubsetItem);
        for (TiesImport.TieImport tieImport : appendList) {
            if (subsetAccessPredicate.test(tieImport.getOtherSubset())) {
                addTie(appendEngine, tieImport);
            }
        }
        junctionEditor.updateJunctions(mainSubsetItem, appendEngine.toJunctionChanges());
    }

    private void addTie(JunctionChangeEngine engine, TiesImport.TieImport tieImport) {
        TiesImport.Other other = tieImport.getOther();
        if (other instanceof TiesImport.IdOther) {
            addIdOther(engine, tieImport, (TiesImport.IdOther) other);
        } else if (other instanceof TiesImport.IdalphaOther) {
            addIdalphaOther(engine, tieImport, (TiesImport.IdalphaOther) other);
        } else if (other instanceof TiesImport.LabelOther) {
            addLabelOther(engine, tieImport, (TiesImport.LabelOther) other);
        }
    }

    private void addIdOther(JunctionChangeEngine engine, TiesImport.TieImport tieImport, TiesImport.IdOther idOther) {
        Subset otherSubset = tieImport.getOtherSubset();
        if (otherSubset instanceof Thesaurus) {
            addIdOther(engine, tieImport, (Thesaurus) otherSubset, idOther);
        } else {
            SubsetItem otherSubsetItem = otherSubset.getSubsetItemById(idOther.getOtherId());
            if (otherSubsetItem != null) {
                engine.addTie(otherSubsetItem, tieImport.getMode(), tieImport.getWeight());
            }
        }
    }

    private void addIdOther(JunctionChangeEngine engine, TiesImport.TieImport tieImport, Thesaurus thesaurus, TiesImport.IdOther idOther) {
        int otherId = idOther.getOtherId();
        Motcle motcle = thesaurus.getMotcleById(otherId);
        if (motcle == null) {
            ExternalSource externalSource = ExternalSourceUtils.getExternalSource(bdfServer, thesaurus);
            if (externalSource != null) {
                motcle = externalSource.getMotcle(fichothequeEditor, thesaurus, otherId);
            }
        }
        if (motcle != null) {
            engine.addTie(motcle, tieImport.getMode(), tieImport.getWeight());
        }
    }

    private void addIdalphaOther(JunctionChangeEngine engine, TiesImport.TieImport tieImport, TiesImport.IdalphaOther idalphaOther) {
        Subset otherSubset = tieImport.getOtherSubset();
        if (!(otherSubset instanceof Thesaurus)) {
            return;
        }
        Thesaurus thesaurus = (Thesaurus) otherSubset;
        String idalpha = idalphaOther.getIdalpha();
        Motcle motcle = thesaurus.getMotcleByIdalpha(idalpha);
        if (motcle == null) {
            ExternalSource externalSource = ExternalSourceUtils.getExternalSource(bdfServer, thesaurus);
            if (externalSource != null) {
                motcle = externalSource.getMotcle(fichothequeEditor, thesaurus, idalpha);
            }
        }
        if (motcle != null) {
            engine.addTie(motcle, tieImport.getMode(), tieImport.getWeight());
        }
    }

    private void addLabelOther(JunctionChangeEngine engine, TiesImport.TieImport tieImport, TiesImport.LabelOther labelOther) {
        Subset otherSubset = tieImport.getOtherSubset();
        if (!(otherSubset instanceof Thesaurus)) {
            return;
        }
        Thesaurus thesaurus = (Thesaurus) otherSubset;
        Label label = labelOther.getLabel();
        Motcle motcle = thesaurus.seekMotcleByLabel(label.getLabelString(), label.getLang());
        if (motcle == null) {
            if (thesaurus.isIdalphaType()) {
                return;
            }
            DynamicEditPolicy dynamicEditPolicy = getDynamicEditPolicy(thesaurus);
            switch (dynamicEditPolicy.getType()) {
                case DynamicEditPolicy.ALLOW_TYPE:
                    ThesaurusEditor thsedit = junctionEditor.getFichothequeEditor().getThesaurusEditor(thesaurus);
                    try {
                        motcle = thsedit.createMotcle(-1, null);
                        thsedit.putLabel(motcle, label);
                    } catch (ExistingIdException | ParseException e) {
                        throw new ShouldNotOccurException(e);
                    }
                    break;
                case DynamicEditPolicy.EXTERNAL_TYPE:
                    ExternalSource externalSource = ExternalSourceUtils.getExternalSource(bdfServer, thesaurus);
                    if (externalSource != null) {
                        motcle = externalSource.getMotcle(fichothequeEditor, thesaurus, label.getLabelString(), label.getLang());
                    }
            }
        }
        if (motcle != null) {
            engine.addTie(motcle, tieImport.getMode(), tieImport.getWeight());
        }
    }

    private DynamicEditPolicy getDynamicEditPolicy(Thesaurus thesaurus) {
        return bdfServer.getPolicyManager().getPolicyProvider().getDynamicEditPolicy(thesaurus);
    }

}
