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

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.Fichotheque;
import net.fichotheque.FichothequeEditor;
import net.fichotheque.Subset;
import net.fichotheque.SubsetItem;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.croisement.CroisementEditor;
import net.fichotheque.importation.LiensImport;
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.tools.croisement.CroisementChangeEngine;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.text.Label;


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

    private LiensImportEngine() {
    }

    static void run(CroisementEditor croisementEditor, SubsetItem mainSubsetItem, LiensImport liensImport, PermissionSummary permissionSummary) {
        Predicate<Subset> subsetAccessPredicate = permissionSummary.getSubsetAccessPredicate();
        FichothequeEditor fichothequeEditor = croisementEditor.getFichothequeEditor();
        Fichotheque fichotheque = fichothequeEditor.getFichotheque();
        boolean withLiage = liensImport.isLiageRemoved();
        List<IncludeKey> removedIncludeKeyList = liensImport.getRemovedIncludeKeyList();
        List<LiensImport.LienImport> replaceList = liensImport.getReplaceLienImportList();
        if ((!removedIncludeKeyList.isEmpty()) || (!replaceList.isEmpty()) || (withLiage)) {
            Set<IncludeKey> clearExisting = new LinkedHashSet<IncludeKey>();
            clearExisting.addAll(removedIncludeKeyList);
            for (LiensImport.LienImport lienImport : replaceList) {
                if (subsetAccessPredicate.test(lienImport.getOtherSubset())) {
                    if (lienImport.isLiageOrigin()) {
                        withLiage = true;
                    } else {
                        clearExisting.add(lienImport.getOriginIncludeKey());
                    }
                }
            }
            if (withLiage) {
                for (Corpus corpus : fichotheque.getCorpusList()) {
                    if (subsetAccessPredicate.test(corpus)) {
                        clearExisting.add(IncludeKey.newInstance(corpus.getSubsetKey()));
                    }
                }
            }
            CroisementChangeEngine replaceEngine = CroisementChangeEngine.clearExistingEngine(mainSubsetItem, clearExisting);
            for (LiensImport.LienImport lienImport : replaceList) {
                if (subsetAccessPredicate.test(lienImport.getOtherSubset())) {
                    addLien(replaceEngine, lienImport, fichothequeEditor);
                }
            }
            croisementEditor.updateCroisements(mainSubsetItem, replaceEngine.toCroisementChanges());
        }
        List<LiensImport.LienImport> appendList = liensImport.getAppendLienImportList();
        if (!appendList.isEmpty()) {
            CroisementChangeEngine appendEngine = CroisementChangeEngine.appendEngine(mainSubsetItem);
            for (LiensImport.LienImport lienImport : appendList) {
                if (subsetAccessPredicate.test(lienImport.getOtherSubset())) {
                    addLien(appendEngine, lienImport, fichothequeEditor);
                }
            }
            croisementEditor.updateCroisements(mainSubsetItem, appendEngine.toCroisementChanges());
        }
    }

    private static void addLien(CroisementChangeEngine engine, LiensImport.LienImport lienImport, FichothequeEditor fichothequeEditor) {
        Subset otherSubset = lienImport.getOtherSubset();
        LiensImport.Other other = lienImport.getOther();
        if (other instanceof LiensImport.IdOther) {
            SubsetItem otherSubsetItem = otherSubset.getSubsetItemById(((LiensImport.IdOther) other).getOtherId());
            if (otherSubsetItem != null) {
                engine.addLien(otherSubsetItem, lienImport.getMode(), lienImport.getWeight());
            }
        } else {
            if (!(otherSubset instanceof Thesaurus)) {
                return;
            }
            Thesaurus thesaurus = (Thesaurus) otherSubset;
            Motcle motcle = null;
            if (other instanceof LiensImport.LabelOther) {
                Label label = ((LiensImport.LabelOther) other).getLabel();
                motcle = thesaurus.seekMotcleByLabel(label.getLabelString(), label.getLang());
                if (motcle == null) {
                    if (thesaurus.isIdalphaType()) {
                        return;
                    }
                    ThesaurusEditor thsedit = fichothequeEditor.getThesaurusEditor(thesaurus);
                    try {
                        motcle = thsedit.createMotcle(-1, null);
                        thsedit.putLabel(motcle, label);
                    } catch (ExistingIdException | ParseException e) {
                        throw new ShouldNotOccurException(e);
                    }
                }

            } else if (other instanceof LiensImport.IdalphaOther) {
                String idalpha = ((LiensImport.IdalphaOther) other).getIdalpha();
                motcle = thesaurus.getMotcleByIdalpha(idalpha);
            }
            if (motcle != null) {
                engine.addLien(motcle, lienImport.getMode(), lienImport.getWeight());
            }
        }
    }

}
