import Locator from '../services/Locator';
import { createDeferredPromise } from '../utils/createDeferredPromise';
import { createStyles, type StyleSheet } from '../utils/styles';
import Activity from './Activity';
import * as fgui from '@popiplay/fairygui-dom-fork';
import { RelationType } from '@popiplay/fairygui-dom-fork';

const style = createStyles<{ layout: string }>({
    layout: 'desktop',
    '(max-height: 550px) and (orientation: landscape)': {
        layout: 'landscape',
    },
    '(orientation: portrait)': {
        layout: 'portrait',
    }
} as unknown as StyleSheet<{ layout: string }>);

/** Shows a loading error popup that refreshes the page on dismissal. */
export default class ShowLoadingError extends Activity
{
    private readonly message: string;

    constructor(message: string)
    {
        super('ShowLoadingError');
        this.message = message;
    }

    override async execute(): Promise<void>
    {
        console.log('ShowLoadingError.execute()');
        const fWindow = fgui.UIPackage.createObject('ErrorPopups', 'ErrorPopupWindow');
        const groot = Locator.groot as unknown as { root: { width: number; height: number; addChild: (child: unknown) => void } };
        const root = groot.root;

        root.addChild(fWindow);
        fWindow.setSize(root.width, root.height);
        fWindow.addRelation(root, RelationType.Size);
        const fWindowLayoutController = fWindow.asCom.getController('layout');

        fWindowLayoutController.setSelectedPage(style.layout);
        const setLayout = (): void =>
        {
            fWindowLayoutController.setSelectedPage(style.layout);
        };

        window.addEventListener('resize', setLayout);

        const fPopup = fWindow.asCom.getChild('popup');
        const fPopupTypeController = fPopup.asCom.getController('type');

        fPopupTypeController.setSelectedPage('ok');

        const fText = fPopup.asCom.getChild('message');

        fText.text = this.message;

        const okBtn = fPopup.asCom.getChild('ok');
        const deferredPromise = createDeferredPromise();

        okBtn.onClick(() =>
        {
            deferredPromise.resolve();
        }, this);

        await deferredPromise.promise;
        window.removeEventListener('resize', setLayout);
        fWindow.dispose();
        location.reload();
    }
}
