import { MgbaHttp } from "../../classes/gba-api/MgbaHttp";
import { Message } from "../../classes/tiktok/Message";
import { WebcastPushConnection } from "tiktok-live-connector";
import { User, FollowerRole } from "../../classes/tiktok/User";
import { Gift } from "../tiktok/Gift";

export class GameController {
    private channelName: string;
    private users: Map<string, User> = new Map<string, User>();
    private webcastPushConnection: WebcastPushConnection;
    private mgbaHttp: MgbaHttp = new MgbaHttp({});
    private availableGifts: Map<number, Gift> = new Map<number, Gift>();

    constructor(channelName: string) {
        this.channelName = channelName;
        this.mgbaHttp = new MgbaHttp({
            baseUrl: "http://localhost:5000",
        });
        
        this.webcastPushConnection = new WebcastPushConnection(
            this.channelName
        );
        
        this.getWebcastPushConnection().getAvailableGifts().then((gifts) => {
            gifts.forEach((gift: any) => {
                this.availableGifts.set(gift.id, new Gift({
                    giftId: gift.id,
                    costDiamonds: gift.diamond_count,
                    name: gift.name,
                }));
            });
        });
    }

    /**
     * Get the WebcastPushConnection object for the TikTok Live connection
     * @returns {WebcastPushConnection} The WebcastPushConnection object for the TikTok Live connection
     */
    private getWebcastPushConnection(): WebcastPushConnection {
        return this.webcastPushConnection;
    }

    /**
     * Get the users Map object, for all users in the TikTok Live that have done some action
     * @returns {Map<string, User>} The Map of users in the TikTok Live
     */
    private getUsers(): Map<string, User> {
        return this.users;
    }

    /**
     * Create a new User object if it does not exist, otherwise return the existing User object
     * @param {string} userId The unique identifier for the user
     * @param {any} data The data object for the user, can be null for searching existing users
     * @returns {User} The User object for the user
     */
    private newUser(userId: string, data: any): User {
        if (this.getUsers().has(userId)) {
            return this.getUsers().get(userId);
        } else {
            let newUser = new User({
                userId: userId,
                displayName: data.nickname,
                username: data.uniqueId,
                isFollower: data.followRole === FollowerRole.FOLLOWER,
                isSubscriber: data.isSubscriber,
            });
            this.getUsers().set(userId, newUser);
            return newUser;
        }
    }

    /**
     * Handle the chat event from the TikTok Live connection
     * @param {any} data The data object for the chat event
     */
    private chatHandler(data: any): void {
        let user = this.newUser(data.userId, data);
        let message = new Message({
            messageId: data.msgId,
            content: data.comment,
        });
        let gameKeyInterpretation = message.getMessageGameKey();
        if (gameKeyInterpretation !== false) {
            this.mgbaHttp
                .buttonTapCreate({
                    key: gameKeyInterpretation.toString(),
                })
                .then(() => {
                    console.log(
                        `${user.getUsername} sent button tap for ${gameKeyInterpretation}`
                    );
                });
        }
    }

    /**
     * Handle the gift event from the TikTok Live connection
     * @param {any} data The data object for the gift event
     */
    private giftHandler(data: any): void {
        
    }

    public start(): void {
        this.getWebcastPushConnection()
            .connect()
            .then(() => {
                console.log("Connected to TikTok Live");
                this.webcastPushConnection.on("chat", this.chatHandler.bind(this));
                this.webcastPushConnection.on("gift", this.giftHandler.bind(this));
            })
            .catch((error) => {
                console.error("Failed to connect", error);
            });
    }
}
