/* FichothequeLib_Import - Copyright (c) 2019-2025 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.from.html.handlers;

import net.fichotheque.corpus.fiche.P;
import net.fichotheque.corpus.fiche.S;
import net.fichotheque.tools.from.html.BlockConversion;
import net.fichotheque.tools.from.html.ElementHandler;
import net.fichotheque.tools.from.html.FlowBuffer;
import net.fichotheque.tools.from.html.TagUtils;
import net.mapeadores.util.text.StringUtils;
import org.jsoup.nodes.Element;


/**
 *
 * @author Vincent Calame
 */
public class BlockquoteHandler extends ElementHandler {

    public final static BlockquoteHandler INSTANCE = new BlockquoteHandler();

    private BlockquoteHandler() {

    }

    @Override
    public int handle(Element element, FlowBuffer flowBuffer) {
        switch (TagUtils.getTagType(element)) {
            case TagUtils.INLINE_TYPE:
                return 0;
            case TagUtils.CDATA_TYPE:
                return 1;
        }
        flowBuffer.flushInline();
        String tagName = element.tagName();
        switch (tagName) {
            case "p":
            case "h1":
            case "h2":
            case "h3":
            case "h4":
            case "h5":
            case "h6":
                addP(element, flowBuffer);
                break;
            case "pre":
                addPre(element, flowBuffer);
                break;
            default:
                flowBuffer.addFicheBlocks(INSTANCE.convertChildNodes(element));
        };
        return 1;
    }

    private void addP(Element element, FlowBuffer flowBuffer) {
        flowBuffer.flushInline();
        P p = new P(P.CITATION);
        BlockConversion.populate(element, p);
        flowBuffer.addFicheBlock(p);

    }

    private void addPre(Element element, FlowBuffer flowBuffer) {
        flowBuffer.flushInline();
        String[] lines = StringUtils.getLineTokens(element.wholeText(), StringUtils.NOTCLEAN);
        P p = new P(P.CITATION);
        boolean next = false;
        for (String line : lines) {
            if (next) {
                p.addS(new S(S.BR));
            } else {
                next = true;
            }
            line = line.trim();
            if (line.length() > 0) {
                S s = new S(S.CODE);
                s.setValue(line);
                p.addS(s);
            }
        }
        flowBuffer.addFicheBlock(p);
    }

}
