import { DomHandler, Parser } from 'htmlparser2';
import decodeHTML from './decode-html.mjs';

/**
 * @param html
 * @returns {classes from html, root element}
 */ function parseHTML(html) {
    const classes = [];
    let htmlElement = null;
    let headElement = null;
    let styleElement = null;
    const handler = new DomHandler(undefined, {}, (element)=>{
        if (element.type === 'tag') {
            switch(element.name){
                case 'html':
                    htmlElement = element;
                    break;
                case 'head':
                    headElement = element;
                    break;
            }
        } else if (element.type === 'style') {
            if (element.attribs.id === 'master') styleElement = element;
        }
        if (element.attribs.class) {
            element.attribs.class.split(' ').forEach((className)=>{
                className = decodeHTML(className);
                if (!classes.includes(className)) classes.push(className);
            });
        }
    });
    new Parser(handler, {
        decodeEntities: false
    }).end(html);
    return {
        classes,
        nodes: handler.root.childNodes,
        htmlElement,
        headElement,
        styleElement
    };
}

export { parseHTML as default };
