/* FichothequeLib_API - 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.extraction.def;

import java.text.ParseException;


/**
 *
 * @author Vincent Calame
 */
public class TagNameInfo {

    public final static short DEFAULT_TYPE = 1;
    public final static short NULL_TYPE = 2;
    public final static short CUSTOM_TYPE = 3;
    public final static TagNameInfo DEFAULT = new TagNameInfo(DEFAULT_TYPE);
    public final static TagNameInfo NULL = new TagNameInfo(NULL_TYPE);
    private final short type;
    private final String customTagName;

    private TagNameInfo(short type) {
        this.type = type;
        this.customTagName = null;
    }

    private TagNameInfo(String customTagName) {
        this.type = CUSTOM_TYPE;
        this.customTagName = customTagName;
    }

    public short getType() {
        return type;
    }

    public String getCustomTagName() {
        return customTagName;
    }

    public static TagNameInfo parse(String tagName) throws ParseException {
        if (tagName == null) {
            return NULL;
        }
        if (tagName.isEmpty()) {
            return DEFAULT;
        }
        check(tagName);
        return new TagNameInfo(tagName);
    }

    private static void check(String s) throws ParseException {
        int charLength = s.length();
        for (int i = 0; i < charLength; i++) {
            char carac = s.charAt(i);
            if (!isCharacter(carac)) {
                if (i == 0) {
                    throw new ParseException("wrong character: " + carac, i);
                }
                if (!isNumber(carac)) {
                    if (i == (charLength - 1)) {
                        throw new ParseException("wrong character: " + carac, i);
                    }
                    if (!isSpecialChar(carac)) {
                        throw new ParseException("wrong character: " + carac, i);
                    }
                }

            }
        }
    }

    private static boolean isCharacter(char carac) {
        return (((carac >= 'a') && (carac <= 'z')) || ((carac >= 'A') && (carac <= 'Z')));
    }

    private static boolean isNumber(char carac) {
        return ((carac >= '0') && (carac <= '9'));
    }

    private static boolean isSpecialChar(char carac) {
        switch (carac) {
            case '-':
            case '_':
                return true;
            default:
                return false;
        }
    }

}
