import axios from "axios";

export class MoorenTV {
    serverAddress: string;
    serverPort: number;
    adminPass: string


    constructor(settings: { serverAddress: string, serverPort: number, adminPass: string }) {
        this.serverAddress = settings.serverAddress;
        this.serverPort = settings.serverPort;
        this.adminPass = settings.adminPass;
    }

    _getBaseURI() {
        return `http://${this.serverAddress}:${this.serverPort}/api/v1/${this.adminPass}/`
    }

    ping(callback: (succeed: boolean) => void) {
        axios.get(this._getBaseURI() + "ping").then(() => {
            callback(true)
        }).catch(() => {
            callback(false)
        })
    }

    getGames(): Promise<{
        [gameID: string]: {
            id: string,
            title: string,
            description: string,
            icon: string,
            category: string,
            pregame: number,
            autojoin: boolean,
            screen: {
                queue: boolean,
                results: boolean,
                banner: boolean,
                stage: {
                    left: number,
                    width: string,
                    height: string
                }
            },
            htdocs: string,
            gamePage: string,
            devicePage: string,
            autoaccept: boolean,
            joinable: boolean
        }
    }> {
        return new Promise((resolve, reject) => {
            axios.get(this._getBaseURI() + 'games').then((response) => {
                if (response.data.succeed == true)
                    resolve(response.data.response)
                else reject('Internal server error')
            }).catch(reject)
        })
    }

    startGame(gameID: string): Promise<void> {
        return new Promise((resolve, reject) => {
            axios.get(this._getBaseURI() + "games/start/" + gameID).then((response) => {
                if (response.data.succeed == true) resolve()
                else reject()
            }).catch(reject)
        })
    }

    stopGame(): Promise<void> {
        return new Promise((resolve, reject) => {
            axios.get(this._getBaseURI() + "games/stop").then((response) => {
                if (response.data.succeed == true) resolve()
                else reject()
            }).catch(reject)
        })
    }
}