import { _decorator, Color, Component, color, ImageAsset, Sprite, SpriteFrame, Texture2D, UITransform } from 'cc';
import HtmlToImage from "html-to-image";

const {ccclass, property, requireComponent} = _decorator;

@ccclass('HTMLRichText')
@requireComponent(Sprite)
export class HTMLRichText extends Component {

    static EventType = {
        AFTER_RENDER: "AFTER_RENDER",
    }

    _html: string = "";

    @property({multiline: true})
    set html(val: string) {
        this._html = val;
        this.setTxt(val);
    }

    get html(): string {
        return this._html;
    }

    @property()
    fontSize: number = 20;

    @property(Color)
    color: Color = color(0, 0, 0, 1);

    protected start() {
        this.setTxt(this._html);
    }

    async setTxt(txt: string) {

        const width = this.node.getComponent(UITransform).width;
        const color = this.color.toCSS("rgba");

        const style = {
            width: `${width}px`,
            fontSize: `${this.fontSize}px`,
            color: color,
        }

        const cssTxt = Object.keys(style).map((key) => {
            return `${key}: ${style[key]}`;
        }).join(";");

        const html = `
            <div id="renderDiv" style="${cssTxt}">
                ${txt}
            </div>
        `
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, "text/html");
        const insDom = document.body.appendChild(doc.documentElement);
        const dom = document.getElementById("renderDiv");

        console.log(dom);

        const canvas = await HtmlToImage.toCanvas(dom, {
            skipFonts: true,
            backgroundColor: "transparent",
        }).catch(() => {
            document.body.removeChild(insDom);
        });

        if (!canvas) return;

        const t2d = new Texture2D();
        t2d.image = new ImageAsset(canvas);

        const sf = new SpriteFrame();
        sf.texture = t2d;

        this.node.getComponent(Sprite).spriteFrame = sf;

        this.node.getComponent(UITransform).setContentSize(canvas.width, canvas.height);

        console.log(canvas.toDataURL());

        this.node.emit(HTMLRichText.EventType.AFTER_RENDER);

    }

}


