/* FichothequeLib_Tools - Copyright (c) 2014-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.Cdatadiv;
import net.fichotheque.tools.parsers.TextContentParser;
import net.fichotheque.utils.FicheUtils;
import net.mapeadores.util.html.HtmlCleaner;


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

    private final TextContentParser textContentParser;
    private final HtmlCleaner htmlCleaner;

    CdatadivParser(TextContentParser textContentParser, HtmlCleaner htmlCleaner) {
        this.textContentParser = textContentParser;
        this.htmlCleaner = htmlCleaner;
    }

    @Override
    public boolean isStartLine(String line) {
        return (line.startsWith("???") || (line.equals("!!!c")) || (line.equals("!!!cdata")));
    }

    @Override
    public void parse(String[] lineArray, int startIndex, Atts initAtts) {
        Cdatadiv cdatadiv = new Cdatadiv();
        FicheUtils.populate(cdatadiv, initAtts);
        int beginIndex = BlockParser.parseZoneBlockElements(cdatadiv, startIndex + 1, lineArray, textContentParser);
        int stop = lineArray.length - 1;
        StringBuilder cdataBuffer = new StringBuilder();
        for (int i = beginIndex; i <= stop; i++) {
            String line = lineArray[i].trim();
            if ((line.startsWith("???")) || (line.startsWith("!!!"))) {
                stop = i;
                break;
            }
            if (cdataBuffer.length() > 0) {
                cdataBuffer.append('\n');
            }
            cdataBuffer.append(line);
        }
        cdatadiv.setCdata(htmlCleaner.cleanHtml(cdataBuffer.toString()));
        setParseResult(stop, cdatadiv);
    }

}
