/* FichothequeLib_Tools - Copyright (c) 2007-2014 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.parsers.span;

import net.fichotheque.corpus.fiche.S;
import net.fichotheque.tools.parsers.TypoParser;
import net.mapeadores.util.text.TypoOptions;


/**
 *
 * @author Vincent Calame
 */
class EmphasisParser extends SpanParser {

    private final TypoOptions typoOptions;

    EmphasisParser(TypoOptions typoOptions) {
        this.typoOptions = typoOptions;
    }

    @Override
    public char getStartChar() {
        return '{';
    }

    @Override
    public SpanParseResult parse(String source, int startIndex) {
        int length = source.length();
        int braceCount = 1;
        int realStart = startIndex + 1;
        for (int i = startIndex + 1; i < length; i++) {
            char carac = source.charAt(i);
            if (carac == '{') {
                braceCount++;
                realStart++;
                if (braceCount == 3) {
                    break;
                }
            } else {
                break;
            }
        }
        short type;
        if (braceCount == 2) {
            type = S.STRONG;
        } else if (braceCount == 3) {
            type = S.EMSTRG;
        } else {
            type = S.EMPHASIS;
        }
        if (realStart == (length - 1)) {
            return getErrorResult(type);
        }
        int stopIndex = getStopIndex(source, realStart, '}');
        if (stopIndex == -1) {
            return getErrorResult(type);
        }
        String value = getValue(source, realStart, stopIndex, '}');
        value = TypoParser.parseTypo(value, typoOptions);
        stopIndex = checkEndIndex(source, stopIndex);
        S span = new S(type);
        span.setValue(value);
        return new SpanParseResult(span, stopIndex);
    }

    private int checkEndIndex(String source, int stopIndex) {
        int length = source.length();
        for (int i = stopIndex + 1; i < length; i++) {
            if (source.charAt(i) == '}') {
                stopIndex++;
            } else {
                break;
            }
        }
        return stopIndex;
    }

    private static SpanParseResult getErrorResult(short type) {
        if (type == S.STRONG) {
            return SpanParseResult.IGNORE_RESULT_2;
        } else if (type == S.EMSTRG) {
            return SpanParseResult.IGNORE_RESULT_3;
        } else {
            return SpanParseResult.IGNORE_RESULT_1;
        }
    }

}
