import { GdRoot } from "../GameData/index.ts";
import { IView, ViewMenu, ViewLevels, ViewGame } from "./index.ts";

export enum EViewType {
    None,
    Menu,
    Levels,
    Game
}

export class ViewManager {
    private _viewMap: Map<EViewType, IView>;
    private _currentViewType: EViewType;
    private _app: HTMLDivElement;

    constructor() {
        this._viewMap = new Map<EViewType, IView>();
        this._currentViewType = EViewType.None;
        this._app = document.getElementById("app") as HTMLDivElement;
    }

    public async loadAsync(gdRoot: GdRoot): Promise<void> {
        const viewManager = this;
        this._viewMap.set(EViewType.Menu, new ViewMenu(await this.loadView("menu"), viewManager));
        this._viewMap.set(EViewType.Levels, new ViewLevels(await this.loadView("levels"), viewManager));
        this._viewMap.set(EViewType.Game, new ViewGame(await this.loadView("game"), gdRoot, viewManager));
    }

    public showView(viewType: EViewType) {
        const oldView = this._viewMap.get(this._currentViewType);
        if (!!oldView) {
            oldView.deactivate();
            this._currentViewType = EViewType.None;
        }

        const newView = this._viewMap.get(viewType);
        if (!!newView) {

            this._app.innerHTML = newView.div;
            this._currentViewType = viewType;
            newView.activate();
        }
    }

    private async loadView(viewName: string): Promise<string> {
        const response = await fetch(`views/${viewName}.html`);
        if (!response.ok) {
            throw new Error(`Failed to load view: ${viewName}`);
        }
        const html = await response.text();
        return html;
    }
}
