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

import net.fichotheque.corpus.fiche.Atts;
import net.fichotheque.corpus.fiche.Code;
import net.fichotheque.corpus.fiche.Ln;
import net.fichotheque.tools.parsers.LineInfo;
import net.fichotheque.tools.parsers.TextContentParser;
import net.fichotheque.utils.FicheUtils;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
class CodeParser extends BlockParser {

    private final LineParser xmlLineParser = new XmlLineParser();
    private final LineParser scriptLineParser = new ScriptLineParser();
    private final LineParser defaultLineParser = new DefaultLineParser();
    private final TextContentParser textContentParser;
    private final boolean withLineNumber;

    CodeParser(TextContentParser textContentParser, boolean withLineNumber) {
        this.textContentParser = textContentParser;
        this.withLineNumber = withLineNumber;
    }

    @Override
    public boolean isStartLine(String line) {
        return line.startsWith("+++");
    }

    @Override
    public void parse(String[] lineArray, int startIndex, Atts initAtts) {
        String firstLine = StringUtils.cleanString(lineArray[startIndex]);
        short type = Code.TYPE_NONE;
        if (firstLine.length() > 3) {
            String params = firstLine.substring(3).trim();
            if (params.length() > 0) {
                type = Code.typeToShort(params.charAt(0));
            }
        }
        Code code = new Code(type);
        FicheUtils.populate(code, initAtts);
        LineParser lineParser = getLineParser(type);
        int beginIndex = BlockParser.parseZoneBlockElements(code, startIndex + 1, lineArray, textContentParser);
        int stop = lineArray.length - 1;
        int clearLineCount = -99999;
        for (int i = beginIndex; i <= stop; i++) {
            String rawLine = lineArray[i];
            String line = StringUtils.cleanString(rawLine);
            if (line.startsWith("+++")) {
                stop = i;
                break;
            }
            LineInfo lineInfo = LineInfo.parse(line, (withLineNumber) ? i : -1);
            String cleanedLine = lineInfo.getCleanedLine();
            if (cleanedLine.length() > 0) {
                if (clearLineCount > 0) {
                    for (int j = 0; j < clearLineCount; j++) {
                        code.add(new Ln(""));
                    }
                }
                clearLineCount = 0;
                Atts atts = lineInfo.getFirstAtts();
                if ((atts != null) && (!atts.hasOnlyAutomaticAtts())) {
                    int idx = rawLine.indexOf(")]");
                    rawLine = rawLine.substring(idx + 2);
                }
                int indent = StringUtils.getIndent(rawLine);
                cleanedLine = testeDebut(cleanedLine);
                code.add(lineParser.parse(cleanedLine, indent, atts));
            } else {
                clearLineCount++;
            }
        }
        setParseResult(stop, code);
    }

    private String testeDebut(String s) {
        if (s.charAt(0) == '\\') {
            if (s.length() > 1) {
                char carac2 = s.charAt(1);
                switch (carac2) {
                    case '+':
                    case '\\':
                    case '[':
                        s = s.substring(1);
                }
            }
        }
        return s;
    }

    private LineParser getLineParser(short type) {
        LineParser lineParser;
        switch (type) {
            case Code.TYPE_XML:
                lineParser = xmlLineParser;
                break;
            case Code.TYPE_SCRIPT:
                lineParser = scriptLineParser;
                break;
            default:
                lineParser = defaultLineParser;
        }
        lineParser.reinit();
        return lineParser;
    }

    private static Ln createLn(String line, int indentation, Atts atts) {
        Ln ln = new Ln(line, indentation);
        FicheUtils.populate(ln, atts);
        return ln;
    }


    private static abstract class LineParser {

        protected int indent = 0;
        protected boolean onComment = false;

        abstract short getType();

        void reinit() {
            indent = 0;
            onComment = false;
        }

        abstract Ln parse(String line, int rawIndent, Atts atts);

    }


    private class DefaultLineParser extends LineParser {

        private DefaultLineParser() {
        }

        @Override
        short getType() {
            return Code.TYPE_NONE;
        }

        @Override
        Ln parse(String line, int rawIndent, Atts atts) {
            return CodeParser.createLn(line, rawIndent, atts);
        }

    }


    private static class XmlLineParser extends LineParser {

        private XmlLineParser() {
        }

        @Override
        short getType() {
            return Code.TYPE_XML;
        }

        @Override
        Ln parse(String line, int rawIndent, Atts atts) {
            int ajout = 0;
            int length = line.length();
            for (int j = 0; j < length - 1; j++) {
                char carac = line.charAt(j);
                char suivant = line.charAt(j + 1);
                if (!onComment) {
                    if (carac == '<') {
                        if (suivant == '/') {
                            ajout--;
                        } else if (suivant == '?') {
                        } else if (suivant == '!') {
                            onComment = true;
                        } else {
                            ajout++;
                        }
                    } else if (carac == '/') {
                        if (suivant == '>') {
                            ajout--;
                        }
                    }
                } else {
                    if (carac == '-') {
                        if (j < (length - 2)) {
                            if ((suivant == '-') && (line.charAt(j + 2) == '>')) {
                                onComment = false;
                            }
                        }
                    }
                }
            }
            if (ajout < 0) {
                indent = indent + ajout;
                if (indent < 0) {
                    indent = 0;
                }
            }
            Ln ln = CodeParser.createLn(line, indent, atts);
            if (ajout > 0) {
                indent = indent + ajout;
            }
            return ln;
        }

    }


    private static class ScriptLineParser extends LineParser {

        private ScriptLineParser() {
        }

        @Override
        short getType() {
            return Code.TYPE_SCRIPT;
        }

        @Override
        Ln parse(String line, int rawIndent, Atts atts) {
            boolean debut = true;
            int indentChange = 0;
            for (int j = 0; j < line.length(); j++) {
                char carac = line.charAt(j);
                if (carac == '{') {
                    indentChange++;
                    debut = false;
                } else if (carac == '}') {
                    if (debut) {
                        indent--;
                    } else {
                        indentChange--;
                    }
                } else if (carac != ' ') {
                    debut = false;
                }
            }
            Ln ln = CodeParser.createLn(line, Math.max(indent, 0), atts);
            indent = indent + indentChange;
            if (indent < 0) {
                indent = 0;
            }
            return ln;
        }

    }

}
