import {moduleId} from "../constants";
import {getSetting, overlayUrl, resultsUrl} from "./utils";

export class Overlays extends FormApplication {

    constructor() {
        super(undefined);
    }

    override async _render(force?: boolean, options?: Application.RenderOptions<FormApplicationOptions>): Promise<any> {
        return super._render(force, options).then(() => {
            this.renderUrls();
        });
    }

    private renderUrls() {
        let room = getSetting("diceTowerRoom") as String;
        let resultOverlay = this.element.find('#result-overlay')
        let diceOverlay = this.element.find('#dice-overlay')
        if (game.user?.isGM) {
            resultOverlay.append($(`
                <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: baseline;">
                    <label for="myResultsId">All Results-Overlay </label>
                    <input type="text" readonly id="myResultsId" style="flex-grow: 1" value="${resultsUrl()}"/>
                </div>
            `))
        }
        game.users?.forEach(u => {
            if (game.user?.isGM || u.id === game.userId) {
                let user = u as foundry.documents.BaseUser;
                diceOverlay.append($(`
                <div id="${room}:${user.id}" style="display: flex; flex-direction: row; justify-content: space-between; align-items: baseline">
                    <label for="${room}:${user.id}url">Dice-Overlay for <strong>${user.name}</strong></label>
                    <input type="text" readonly style="flex-grow: 1" value="${overlayUrl(u.id)}">
                </div>
                
            `))

            resultOverlay.append($(`
                <div style="display: flex; flex-direction: row; justify-content: space-between; align-items: baseline;">
                    <label for="myResultsId">My-Results-Overlay </label>
                    <input type="text" readonly id="myResultsId" style="flex-grow: 1" value="${resultsUrl(u.id)}"/>
                </div>
            `))
            }
        })
    }

    static override get defaultOptions(): FormApplicationOptions {
        return foundry.utils.mergeObject(super.defaultOptions, {
            id: "dice-tower-overlays",
            title: "DICETOWER.overlaysTitle",
            template: `modules/${moduleId}/templates/dice-tower-overlays.hbs`,
            width: 800,
            height: 400,
        }) as FormApplicationOptions;
    }

    protected _updateObject(_event: Event, _formData: object | undefined): Promise<unknown> {
            return Promise.resolve(undefined);
        }
}
