import '@ungap/custom-elements';
import * as fgui from '@popiplay/fairygui-dom-fork';

import type { Service } from '../types';

type FairyGRoot = typeof fgui.GRoot.inst;

/** Wraps FairyGUI's global root and keeps it scaled to the browser window. */
export default class GRoot implements Service
{
    public name = 'groot';
    public readonly serviceType = 'groot';
    public readonly root: FairyGRoot;

    private readonly resizeHandler: () => void;

    constructor()
    {
        this.root = fgui.GRoot.inst;
        this.resizeHandler = this.resize.bind(this);
        window.addEventListener('resize', this.resizeHandler);
        this.resize();
    }

    public resize(): void
    {
        const width = window.innerWidth;
        const height = window.innerHeight;
        const scale = height / 1080;

        this.root.setScale(scale, scale);
        this.root.setSize(width / scale, height / scale);
    }

    public dispose(): void
    {
        window.removeEventListener('resize', this.resizeHandler);
    }
}
