/*  FichothequeLib_Import - Copyright (c) 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;

import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;


/**
 *
 * @author Vincent Calame
 */
public final class TagUtils {

    public final static short BLOCK_TYPE = 1;
    public final static short INLINE_TYPE = 2;
    public final static short CDATA_TYPE = 3;

    private TagUtils() {

    }

    public static short getTagType(Element element) {
        switch (element.tagName()) {
            case "iframe":
            case "audio":
            case "video":
            case "object":
                return CDATA_TYPE;
            case "del":
            case "ins":
                if (containsBlock(element)) {
                    return BLOCK_TYPE;
                } else {
                    return INLINE_TYPE;
                }
            case "br":
                return INLINE_TYPE;
            default:
                if (element.isBlock()) {
                    return BLOCK_TYPE;
                } else {
                    return INLINE_TYPE;
                }

        }
    }

    public static boolean isInline(Element element) {
        return (getTagType(element) == INLINE_TYPE);
    }

    public static Element getLoneChild(Element parent) {
        if (parent.childNodeSize() == 1) {
            Node child = parent.childNode(0);
            if (child instanceof Element) {
                return (Element) child;
            }
        }
        Element loneChild = null;
        for (Node node : parent.childNodes()) {
            if (node instanceof Element) {
                if (loneChild == null) {
                    loneChild = (Element) node;
                } else {
                    return null;
                }
            } else if (node instanceof TextNode) {
                String text = ((TextNode) node).text();
                if (text.trim().length() > 0) {
                    return null;
                }
            }
        }
        return loneChild;
    }

    private static boolean containsBlock(Element element) {
        for (Element child : element.children()) {
            if (!isInline(child)) {
                return true;
            }
        }
        return false;
    }


}
