import {render, Host} from "../vdom";

// TODO the custom-element class could be removed, and its functionality implemented through the @defineElement decorator
// Currently there are issues:  if a custom-element reimplements the connectedCallback, they need to magically know that
// they should run the super.connectCallback(). to make sure it actually gets rendered on mounting to the DOM...

/**
 * This CustomElement class is to avoid having to do an ugly workaround in every custom-element:
 * Which would be replacing 'HTMLElement' with '(class extends HTMLElement{})'
 *
 * Also, it is a good starting point for implementing render() functionality, listening to props, state changes, events and whatnot (use decorators)
 */
export class CustomElement extends HTMLElement {
    connectedCallback() {
        this.update();
    }
    disconnectedCallback(){
    
    }
    
    #markedDirty;
    #renderedVNode;
    update(){
        if (this.render) {
            let newVNode = this.render();
            if(newVNode.type !== Host){
                newVNode = {type: Host, children: newVNode instanceof Array? newVNode : [newVNode]};
            }
            render(newVNode, {
                host: this,
                old: this.#renderedVNode,
            });
            this.#renderedVNode = newVNode;
        }
        this.#markedDirty=false;
    }
    markDirty() {
        if (!this.#markedDirty) {
            this.#markedDirty = requestAnimationFrame(() => this.update());
        }
    }
}

