import {moduleId} from "../constants";
import {DiceTower} from "../types";
import {SocketType} from "../types/socketType";

export function currentActor() {
    return ((game as Game).modules.get(moduleId) as unknown as DiceTower).controls.find('#dice-tower-actor').val()
}

export function getDiceSettings(): Dice {
    let settingFor = currentActor();
    if (settingFor) {
        return Object.assign((getSetting("default-dice") as Dice), getSetting(`${settingFor}-dice`, "default-dice"));
    } else {
        return getSetting("default-dice")
    }
}

export async function setDiceSettings(settings: Dice): Promise<void> {
    let settingFor = currentActor();
    if (settingFor) {
        if (game.user?.isGM) {
            await setSetting(`${settingFor}-dice`, settings, true);
            ui.notifications?.info("Dice-Customization saved", {localize: true})
        } else {
            ((game as Game).modules.get(moduleId) as unknown as DiceTower).diceSocket.emit({
                type: SocketType.SETTINGS,
                from: game.userId as string,
                payload: {
                    key: settingFor,
                    value: settings
                }
            })
            ui.notifications?.info("Dice-Customization save-request sent", {localize: true})
        }
        ((game as Game).modules.get(moduleId) as unknown as DiceTower).diceSocket.emit({
            type: SocketType.RERENDER,
            from: game.userId as string,
            payload: {
                key: settingFor
            }
        }, 1000)
    }
}

export function getSetting<D>(key: string, defaultKey?: any): D {
    if (defaultKey) {
        try {
            getSetting(key)
        } catch (_) {
            registerSetting(key, getSetting(defaultKey));
        }
        return getSetting(key)
    } else {
        // @ts-ignore
        return game.settings?.get(moduleId, key) as D
    }
}

export async function setSetting(key: string, value: any, force = false) {
    if (force) {
        try {
            await setSetting(key, value, false)
        } catch (e) {
            registerSetting(key, value);
        }
    } else {
        // @ts-ignore
        await game.settings?.set(moduleId, key, value);
    }
}

export function registerSetting(key: string, value: any, options: {scope: 'client'|'world', config: boolean} = { scope: "world", config: false }) {
    // @ts-ignore
    game.settings?.register(moduleId, key, {
        name: `DICETOWER.${key}Name`,
        scope: options.scope,
        default: value,
        type: typeof value === 'string' ? String : typeof value === 'boolean' ? Boolean : typeof value === 'number' ? Number : Object,
        config: options.config
    })
}

export function overlayUrl(user: string): string {
    let url = getSetting("diceTowerUrl") as String;
    let room = getSetting("diceTowerRoom") as String;
    return url + '/overlay/' + room + ':' + user + '?scale=10&clearAfter=30'
}


export function resultsUrl(user?: string): string {
    let url = getSetting("diceTowerUrl") as String;
    let room = getSetting("diceTowerRoom") as String;
    return url + '/overlay/' + room + 'results' + (user ? '?user=' + user : '')
}
