import {Container, Transform} from 'pixi.js';
import Locator from '../services/Locator';
import { div } from './htmlUtils';

/** Syncs a DOM node with the transform of a Pixi container. */
export class PixiHtmlContainer extends Container
{
    readonly element: HTMLDivElement;

    private readonly domTransform: Transform;

    constructor(parentDom: HTMLElement | null | undefined, className: string, style: Partial<CSSStyleDeclaration> = {})
    {
        super();
        this.element = div(className);
        this.domTransform = new Transform();
        Object.assign(this.element.style, style);
        parentDom?.append(this.element);
        //@ts-expect-error event type
        Locator.viewport.on('resize', this.updateTransform, this);
    }

    /** Keeps the DOM element aligned with the Pixi world transform. */
    override updateTransform(): void
    {
        super.updateTransform();
        const globalTransform = this.parent?.transform.worldTransform;

        if (!globalTransform)
        {
            return;
        }

        const decomposition = globalTransform.decompose(this.domTransform);
        const transform = `scale(${decomposition.scale.x}, ${decomposition.scale.y}) translate(-50%, -50%)`;

        this.element.style.transform = transform;
    }

    override destroy(...args: Parameters<Container['destroy']>): void
    {
        //@ts-expect-error event type
        Locator.viewport.off('resize', this.updateTransform, this);
        super.destroy(...args);
    }
}
