import {moduleId} from "../constants";
import {SocketMessage} from "../types/SocketMessage";
import {SocketType} from "../types/socketType";
import {currentActor, setSetting} from "./utils";
import {DiceTower} from "../types";

export class DiceSocket {

    static socketName = `module.${moduleId}`;

    constructor() {
        game.socket?.on(DiceSocket.socketName, this.onData)
    }

    private async onData(data: SocketMessage) {
        switch (data.type) {
            case SocketType.SETTINGS:
                if (game.user?.isGM && game.actors?.get(data.payload.key)?.testUserPermission(game.users?.get(data.from) as foundry.documents.BaseUser, "OWNER")) {
                    setSetting(`${data.payload.key}-dice`, data.payload.value, true);
                }
                break;
            case SocketType.RERENDER:
                if (data.payload.key == currentActor() && ((game as Game).modules.get(moduleId) as unknown as DiceTower).customization.rendered) {
                    console.log(`rerendering ${data.payload.key}`);
                    await ((game as Game).modules.get(moduleId) as unknown as DiceTower).customization.close();
                    ((game as Game).modules.get(moduleId) as unknown as DiceTower).customization.render(true);
                }
        }
    }

    emit(messaage: SocketMessage, timeout = 0) {
        game.socket?.timeout(timeout).emit(DiceSocket.socketName, messaage)
    }
}
