/* BdfServer_Commands - Copyright (c) 2012-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.commands.thesaurus;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import net.fichotheque.FichothequeEditor;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.thesaurus.ParentRecursivityException;
import net.fichotheque.thesaurus.Thesaurus;
import net.fichotheque.thesaurus.ThesaurusEditor;
import net.fichotheque.thesaurus.policies.DynamicEditPolicy;
import net.fichotheque.tools.thesaurus.ThesaurusTools;
import net.fichotheque.utils.ThesaurusUtils;
import net.mapeadores.util.exceptions.ImplementationException;
import net.mapeadores.util.localisation.Langs;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.Label;


/**
 *
 * @author Vincent Calame
 */
public class ThesaurusCleaningCommand extends AbstractBdfCommand {

    public final static String COMMANDNAME = "ThesaurusCleaning";
    public final static String COMMANDKEY = "_ THS-06";
    private Thesaurus thesaurus;

    public ThesaurusCleaningCommand(BdfServer bdfServer, RequestMap requestMap) {
        super(bdfServer, requestMap);
    }

    @Override
    public boolean needSynchronisation() {
        return true;
    }

    @Override
    protected void doCommand() throws ErrorMessageException {
        Integer[] result;
        try (EditSession session = startEditSession(Domains.THESAURUS, COMMANDNAME)) {
            result = clean(session.getFichothequeEditor().getThesaurusEditor(thesaurus));
        }
        setDone("_ done.thesaurus.thesauruscleaning", (Object[]) result);
        putResultObject(THESAURUS_OBJ, thesaurus);
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        thesaurus = requestHandler.getMandatoryThesaurus();
        checkSubsetAdmin(thesaurus);
        if (!checkConfirmation()) {
            throw BdfErrors.error("_ error.empty.confirmationcheck_remove");
        }
    }

    private Integer[] clean(ThesaurusEditor thesaurusEditor) {
        FichothequeEditor fichothequeEditor = thesaurusEditor.getFichothequeEditor();
        int nbretransfert = 0;
        DynamicEditPolicy dynamicEditPolicy = bdfServer.getPolicyManager().getPolicyProvider().getDynamicEditPolicy(thesaurus);
        Thesaurus[] checkThesaurusArray = ThesaurusUtils.getCheckThesaurusArray(bdfServer.getFichotheque(), dynamicEditPolicy);
        if (checkThesaurusArray != null) {
            for (Motcle motcle : thesaurus.getMotcleList()) {
                boolean done = transfer(fichothequeEditor, motcle, checkThesaurusArray);
                if (done) {
                    nbretransfert++;
                }
            }
        }
        int nbresuppression = ThesaurusUtils.removeRemoveableMotcle(thesaurusEditor);
        int nbrefusion = 0;
        if (!thesaurus.isIdalphaType()) {
            Langs langs = bdfServer.getThesaurusLangChecker().getAuthorizedLangs(thesaurus);
            for (Motcle motcle : thesaurus.getMotcleList()) {
                boolean done = merge(fichothequeEditor, motcle, langs);
                if (done) {
                    nbrefusion++;
                }
            }
        }
        Integer[] result = new Integer[3];
        result[0] = nbretransfert;
        result[1] = nbresuppression;
        result[2] = nbrefusion;
        return result;
    }

    private boolean merge(FichothequeEditor fichothequeEditor, Motcle motcle, Langs langs) {
        int labelLength = motcle.getLabels().size();
        if (labelLength != 1) {
            return false;
        }
        Label label = motcle.getLabels().get(0);
        Motcle destination = thesaurus.getMotcleByLabel(label.getLabelString(), label.getLang());
        if (destination.equals(motcle)) {
            return false;
        }
        Motcle source = motcle;
        if (ThesaurusUtils.isDescendant(destination, motcle)) {
            source = destination;
            destination = motcle;
        }
        try {
            ThesaurusTools.merge(fichothequeEditor, source, destination, langs);
        } catch (ParentRecursivityException pre) {
            throw new ImplementationException(pre);
        }
        return true;
    }

    private boolean transfer(FichothequeEditor fichothequeEditor, Motcle motcle, Thesaurus[] verifThesaurusArray) {
        int labelLength = motcle.getLabels().size();
        if (labelLength != 1) {
            return false;
        }
        Label label = motcle.getLabels().get(0);
        for (Thesaurus verifThesaurus : verifThesaurusArray) {
            Motcle destination = verifThesaurus.getMotcleByLabel(label.getLabelString(), label.getLang());
            if (destination != null) {
                try {
                    Langs langs = bdfServer.getThesaurusLangChecker().getAuthorizedLangs(destination.getThesaurus());
                    ThesaurusTools.merge(fichothequeEditor, motcle, destination, langs);
                } catch (ParentRecursivityException pre) {
                    throw new ImplementationException(pre);
                }
                return true;
            }
        }
        return false;
    }

}
