/* FichothequeLib_API - Copyright (c) 2006-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 net.fichotheque.include;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import net.fichotheque.SubsetKey;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
public final class IncludeKey implements IncludeMode {

    private final static Map<String, IncludeKey> internMap = new HashMap<String, IncludeKey>();
    private final String includeKeyString;
    private final SubsetKey subsetKey;
    private final String mode;
    private final int weightFilter;

    private IncludeKey(SubsetKey subsetKey, String mode, int weightFilter) {
        this.subsetKey = subsetKey;
        this.includeKeyString = toString(subsetKey.getKeyString(), mode, weightFilter);
        this.mode = mode;
        this.weightFilter = weightFilter;
        intern(this);
    }

    public SubsetKey getSubsetKey() {
        return subsetKey;
    }

    @Override
    public String getMode() {
        return mode;
    }

    @Override
    public int getWeightFilter() {
        return weightFilter;
    }

    public boolean hasWeightFilter() {
        return (weightFilter != -1);
    }

    public String getKeyString() {
        return includeKeyString;
    }

    @Override
    public String toString() {
        return includeKeyString;
    }

    @Override
    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }
        if (other == this) {
            return true;
        }
        if (other.getClass() != this.getClass()) {
            return false;
        }
        IncludeKey otherKey = (IncludeKey) other;
        return (otherKey.includeKeyString.equals(this.includeKeyString));
    }

    @Override
    public int hashCode() {
        return includeKeyString.hashCode();
    }

    public static IncludeKey parse(String key) throws ParseException {
        if (key.equals("association")) {
            key = "addenda_doc";
        }
        IncludeKey current = internMap.get(key);
        if (current != null) {
            return current;
        }
        int oldIdx = key.indexOf(':');
        if (oldIdx != -1) {
            return parse(key.replace(':', '_'));
        }
        String[] tokens = StringUtils.getTokens(key, '_', StringUtils.NOTCLEAN);
        int length = tokens.length;
        if (length < 2) {
            throw new ParseException("Missing underscore", 0);
        }
        if (length > 4) {
            throw new ParseException("Too many underscore", 0);
        }
        String token1 = tokens[0];
        String token2 = tokens[1];
        short category;
        try {
            category = SubsetKey.categoryToShort(token1);
        } catch (IllegalArgumentException iae) {
            throw new ParseException("Unknown subset category", 0);
        }
        SubsetKey subsetKey;
        try {
            subsetKey = SubsetKey.parse(category, token2);
        } catch (ParseException pe) {
            throw new ParseException("Wrong subset name", token1.length() + 1);
        }
        String mode = "";
        int weightFilter = -1;
        if (length == 3) {
            String token3 = tokens[2];
            try {
                weightFilter = Integer.parseInt(token3);
                if (weightFilter < 1) {
                    throw new ParseException("Wrong weight filter", token1.length() + token2.length() + 1);
                }
            } catch (NumberFormatException nfe) {
                try {
                    StringUtils.checkTechnicalName(token3, false);
                    mode = token3;
                    weightFilter = - 1;
                } catch (ParseException pe) {
                    throw new ParseException("Wrong mode", token1.length() + token2.length() + 1);
                }
            }
        } else if (length == 4) {
            String token3 = tokens[2];
            String token4 = tokens[3];
            try {
                StringUtils.checkTechnicalName(token3, false);
                mode = token3;
            } catch (ParseException pe) {
                throw new ParseException("Wrong mode", token1.length() + token2.length() + 1);
            }
            try {
                weightFilter = Integer.parseInt(token4);
                if (weightFilter < 1) {
                    throw new ParseException("Wrong weight filter", token1.length() + token2.length() + token3.length() + 1);
                }
            } catch (NumberFormatException nfe) {
                throw new ParseException("Wrong weight filter", token1.length() + token2.length() + token3.length() + 1);
            }
        }
        return new IncludeKey(subsetKey, mode, weightFilter);
    }

    /**
     * Équivalent de parse() mais en envoyant IllegalArgumentException plutôt
     * que ParseException. à utiliser quand on est sûr de la syntaxe et permet
     * d'éviter un try {} catch {}
     */
    public static IncludeKey build(String key) {
        try {
            return parse(key);
        } catch (ParseException pe) {
            throw new IllegalArgumentException(pe.getMessage());
        }
    }

    public static IncludeKey newInstance(SubsetKey subsetKey) {
        return newInstance(subsetKey, "", -1);
    }

    /**
     *
     * @throws IllegalArgumentException si subsetKey ou mode sont illégaux
     */
    public static IncludeKey newInstance(SubsetKey subsetKey, String mode, int weightFilter) {
        String key = toString(subsetKey.getKeyString(), mode, weightFilter);
        IncludeKey current = internMap.get(key);
        if (current != null) {
            return current;
        }
        if ((weightFilter == 0) || (weightFilter < -1)) {
            throw new IllegalArgumentException();
        }
        if (mode.length() > 0) {
            try {
                StringUtils.checkTechnicalName(mode, false);
            } catch (ParseException pe) {
                throw new IllegalArgumentException("Wrong mode: " + mode);
            }
        }
        return new IncludeKey(subsetKey, mode, weightFilter);
    }

    private synchronized static void intern(IncludeKey includeKey) {
        internMap.put(includeKey.includeKeyString, includeKey);
    }

    private static String toString(String name, String mode, int weightFilter) {
        if (mode.length() > 0) {
            if (weightFilter < 1) {
                return name + "_" + mode;
            } else {
                return name + "_" + mode + "_" + weightFilter;
            }
        } else {
            if (weightFilter < 1) {
                return name;
            } else {
                return name + "_" + weightFilter;
            }
        }
    }

}
