/* 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 java.util.ArrayList;
import java.util.List;
import net.fichotheque.SubsetKey;
import net.fichotheque.thesaurus.Thesaurus;
import net.fichotheque.thesaurus.policies.DynamicEditPolicy;
import net.fichotheque.tools.externalsource.ExternalSourceDefBuilder;
import net.fichotheque.tools.thesaurus.DynamicEditPolicyBuilder;
import net.fichotheque.utils.ThesaurusUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "ThesaurusPolicy";
    public final static String COMMANDKEY = "_ THS-05";
    public final static String LANGLIST_PARAMNAME = "langlist";
    public final static String POLICY_PARAMNAME = "policy";
    public final static String TRANSFERKEY_PARAMNAME = "transferkey";
    public final static String CHECKKEYLIST_PARAMNAME = "checkkeylist";
    public final static String EXTERNALTYPE_PARAMNAME = "externaltype";
    public final static String EXTERNAL_PARAMPREFIX = "external_";
    public final static String POLICY_NONE_PARAMVALUE = "none";
    public final static String POLICY_ALLOW_PARAMVALUE = "allow";
    public final static String POLICY_CHECK_PARAMVALUE = "check";
    public final static String POLICY_TRANSFER_PARAMVALUE = "transfer";
    public final static String POLICY_EXTERNAL_PARAMVALUE = "external";
    private Thesaurus thesaurus;
    private DynamicEditPolicy newPolicy;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        try (EditSession session = startEditSession(Domains.THESAURUS, COMMANDNAME)) {
            session.getBdfServerEditor().setSubsetPolicy(thesaurus.getSubsetKey(), newPolicy);
        }
        setDone("_ done.thesaurus.thesauruspolicy");
        putResultObject(THESAURUS_OBJ, thesaurus);
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        thesaurus = requestHandler.getMandatoryThesaurus();
        String policyParam = getMandatory(POLICY_PARAMNAME);
        switch (policyParam) {
            case POLICY_NONE_PARAMVALUE:
                newPolicy = ThesaurusUtils.NONE_POLICY;
                break;
            case POLICY_ALLOW_PARAMVALUE:
                newPolicy = ThesaurusUtils.ALLOW_POLICY;
                break;
            case POLICY_TRANSFER_PARAMVALUE:
                newPolicy = getTransferPolicy();
                break;
            case POLICY_CHECK_PARAMVALUE:
                newPolicy = getCheckPolicy();
                break;
            case POLICY_EXTERNAL_PARAMVALUE:
                newPolicy = getExternalPolicy();
                break;
            default:
                throw BdfErrors.unknownParameterValue(POLICY_PARAMNAME, policyParam);
        }
        if (!newPolicy.isValid(thesaurus)) {
            throw BdfErrors.unsupportedParameterValue(POLICY_PARAMNAME, policyParam);
        }
    }

    private DynamicEditPolicy getTransferPolicy() throws ErrorMessageException {
        String transferKeyParam = getMandatory(TRANSFERKEY_PARAMNAME);
        Thesaurus transferThesaurus = fichotheque.getThesaurus(transferKeyParam);
        if ((transferThesaurus == null) || (!transferThesaurus.isBabelienType())) {
            throw BdfErrors.unknownParameterValue(TRANSFERKEY_PARAMNAME, transferKeyParam);
        }
        return DynamicEditPolicyBuilder.buildTransfer(transferThesaurus.getSubsetKey());
    }

    private DynamicEditPolicy getCheckPolicy() throws ErrorMessageException {
        String[] array = requestHandler.getTokens(CHECKKEYLIST_PARAMNAME);
        if (array.length == 0) {
            throw BdfErrors.emptyMandatoryParameter(CHECKKEYLIST_PARAMNAME);
        }
        List<SubsetKey> list = new ArrayList<SubsetKey>();
        for (String thesaurusName : array) {
            Thesaurus verifThesaurus = fichotheque.getThesaurus(thesaurusName);
            if ((verifThesaurus != null) && (!verifThesaurus.isIdalphaType())) {
                list.add(verifThesaurus.getSubsetKey());
            }
        }
        if (list.isEmpty()) {
            throw BdfErrors.wrongParameterValue(CHECKKEYLIST_PARAMNAME, list.toString());
        }
        return DynamicEditPolicyBuilder.buildCheck(list);
    }

    private DynamicEditPolicy getExternalPolicy() throws ErrorMessageException {
        String externalType = requestHandler.getTrimedParameter(EXTERNALTYPE_PARAMNAME);
        if (externalType.isEmpty()) {
            return ThesaurusUtils.NONE_POLICY;
        }
        ExternalSourceDefBuilder externalSourceDefBuilder = new ExternalSourceDefBuilder(externalType);
        String prefix = EXTERNAL_PARAMPREFIX + externalType + "|";
        for (String paramName : requestHandler.getParameterNameSet()) {
            if (paramName.startsWith(prefix)) {
                externalSourceDefBuilder.addParam(paramName.substring(prefix.length()), requestHandler.getMandatoryParameter(paramName));
            }
        }
        return DynamicEditPolicyBuilder.buildExternal(externalSourceDefBuilder.toExternalSourceDef());
    }

}
