import renderer from "dom-serializer";
import * as htmlparser2 from "htmlparser2";

function encodeSpecialCharacters(htmlContent: string) {
    if (!htmlContent || htmlContent === "") {
        return htmlContent;
    }
    const dom = htmlparser2.parseDocument(htmlContent);
    return renderer(dom);
}

function extractBody(htmlContent: string) {
    if (!htmlContent || htmlContent === "") {
        return htmlContent;
    }
    const bodyStart = htmlContent.indexOf("<body");
    const bodyEnd = htmlContent.indexOf("</body>");

    if (bodyStart < 0 || bodyEnd < 0) {
        return htmlContent;
    }

    const bodyStartClosing = htmlContent.indexOf(">", bodyStart);
    return htmlContent.substring(bodyStartClosing + 1, bodyEnd);
}

export default function transformContentHtml(htmlContent: string) {
    const encoded = encodeSpecialCharacters(htmlContent);
    return extractBody(encoded);
}
