/* FichothequeLib_Tools - Copyright (c) 2022 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.tools.extraction.syntaxes;

import java.io.IOException;
import java.text.ParseException;
import net.fichotheque.utils.SyntaxUtils;
import net.mapeadores.util.attr.AttributeKey;


/**
 *
 * @author Vincent Calame
 */
public final class AttributeResolver {

    private AttributeResolver() {

    }

    public static String resolve(String value) {
        if (value.isEmpty()) {
            return "";
        }
        StringBuilder buf = new StringBuilder();
        try {
            resolve(buf, value);
        } catch (IOException ioe) {

        }
        return buf.toString();
    }

    public static void resolve(Appendable appendable, String value) throws IOException {
        int idx = value.indexOf('=');
        String keyPart;
        String valuePart;
        boolean withOperator = false;
        if (idx != -1) {
            withOperator = true;
            keyPart = value.substring(0, idx).trim();
            valuePart = value.substring(idx + 1).trim();
        } else {
            keyPart = value.trim();
            valuePart = "";
        }
        try {
            AttributeKey attributeKey = AttributeKey.parse(keyPart);
            SyntaxUtils.appendSpan(appendable, "cm-atom", attributeKey.getNameSpace());
            SyntaxUtils.appendSpan(appendable, "cm-operator", ":");
            SyntaxUtils.appendSpan(appendable, "cm-def", attributeKey.getLocalKey());
        } catch (ParseException pe) {
            SyntaxUtils.appendErrorSpan(appendable, keyPart);
        }
        if (withOperator) {
            SyntaxUtils.appendSpan(appendable, "cm-operator", "=");
        }
        if (valuePart.length() > 0) {
            SyntaxUtils.appendSpan(appendable, "cm-quote", valuePart);
        }
    }

}
