const express = require("express")
const app = new express()
const RPC = require('discord-rpc');
const client = new RPC.Client({ transport: 'ipc' });
const { defaultActivity } = require("./lib/defaults");
const { teamsIndex } = require("./lib/teams")
const port = process.env.PORT || 60881
const { getState, updateState, preloadState } = require("./lib/utils");
const fs = require("node:fs");
const { get } = require("node:http");


app.get("/changeTeams/regular-participant/:teamSlug", (res, req) => {
    if (req.teamSlug == "sprecators") {
        client.setActivity({
            pid: process.pid,
            activity: teamsIndex.regularEvents.sprecators
        })
        updateState(teamsIndex.regularEvents.sprecators)
    } else {
        res.status(404).json({
            ok: false,
            error: "Team not found on index."
        })
    }
})

app.get("/getState", (req, res) => {
    res.json(getState())
})

app.get("/getState/preloaded", (req, res) => {
    res.json(preloadState)
})


client.on('ready', async () => {
    fs.stat('rpcState.json', function(err, stat) {
        if (err == null) {
            console.log('info: State file exists, preloading from previous state');
            client.request("SET_ACTIVITY", { pid: process.pid, activity: getState() });
        } else {
            client.request("SET_ACTIVITY", { pid: process.pid, activity: defaultActivity });
            console.log("info: Using default activity for state due to file issues");
            updateState(defaultActivity)
        }
    });
});
client.on('connected', async () => {
    console.log("info: Connected to Discord RPC");
});
app.listen(port, () => {
    console.log("info: REST API is up at http://localhost:"+port+", see README.md and docs directory")
    console.log("info: for the API docs.")
})


// Uses the unofficial MCC.Live OAuth client ID from Andrei Jiroh.
client.login({ clientId: "952456760948559932" });
