/* 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 java.net.URI;
import java.net.URISyntaxException;
import net.fichotheque.corpus.fiche.S;


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

    HttpParser() {
    }

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

    @Override
    public SpanParseResult parse(String source, int startIndex) {
        int length = source.length();
        boolean isHttps = false;
        if (startIndex > length - 10) {
            return SpanParseResult.IGNORE_RESULT_1;
        }
        int currentIndex = startIndex + 1;
        if (source.charAt(currentIndex) != 't') {
            return SpanParseResult.IGNORE_RESULT_1;
        }
        currentIndex++;
        if (source.charAt(currentIndex) != 't') {
            return SpanParseResult.IGNORE_RESULT_1;
        }
        currentIndex++;
        if (source.charAt(currentIndex) != 'p') {
            return SpanParseResult.IGNORE_RESULT_1;
        }
        currentIndex++;
        if (source.charAt(currentIndex) == 's') {
            isHttps = true;
            currentIndex++;
        }
        if (source.charAt(currentIndex) != ':') {
            return SpanParseResult.IGNORE_RESULT_1;
        }
        currentIndex++;
        if (source.charAt(currentIndex) != '/') {
            return SpanParseResult.IGNORE_RESULT_1;
        }
        currentIndex++;
        if (source.charAt(currentIndex) != '/') {
            return SpanParseResult.IGNORE_RESULT_1;
        }
        currentIndex++;
        char prems = source.charAt(currentIndex);
        if (!checkCharInUrl(prems)) {
            return SpanParseResult.IGNORE_RESULT_1;
        }
        currentIndex++;
        StringBuilder refBuffer = new StringBuilder();
        if (isHttps) {
            refBuffer.append("https://");
        } else {
            refBuffer.append("http://");
        }
        refBuffer.append(prems);
        int stopIndex = appendUrl(source, refBuffer, currentIndex);
        S span = new S(S.LINK);
        String ref = refBuffer.toString();
        span.setRef(ref);
        String value;
        try {
            URI uri = new URI(ref);
            value = uri.getHost() + uri.getPath();
        } catch (URISyntaxException use) {
            if (isHttps) {
                value = ref.substring(8);
            } else {
                value = ref.substring(7);
            }
        }
        span.setValue(value);
        return new SpanParseResult(span, stopIndex);
    }

}
