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>");
    return bodyStart >= 0 && bodyEnd >= 0 ? htmlContent.substring(bodyStart + 6, bodyEnd) : htmlContent;
}

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