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

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

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


client.on('ready', async () => {
    fs.stat('rpcState.json', (err, stat) => {

        if (err == null) {
            resetStartTimestamp = {
                details: getState().details,
                assets: getState().assets,
                state: getState().state,
                buttons: getState().buttons,
                timestamps: {
                    start: timestampStart()
                }
            }
            console.log('info: State file exists, preloading from previous state');
            /** Check if timestamp.start from getState is longer than six hours to trigger reset. */
            if (sixHoursAgo > getState().timestamps.start) {
                console.log("info: timestamp.start from state file is less than 6 hours ago, preloading")
                client.request("SET_ACTIVITY", { pid: process.pid, activity: getState() });
            } else if (sixHoursAgo < getState().timestamps.start) {
                console.log('info: timestamp.start from state file is longer than 6 hours, resetting...')
                updateState(resetStartTimestamp)
            }
        } 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.once('connected', async () => {
    console.log("info: Connected to Discord local RPC server");
});
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. Please do not make API calls yet until the API server successfully")
    console.log("info: connects to Discord RPC to avoid issues..")
})

// Uses the unofficial MCC.Live OAuth client ID from Andrei Jiroh.
// Uses discord-auto-rpc behind the scenes to attempt to connect to RPC and wait until Discord is up.
client.endlessLogin({ clientId: "952456760948559932" });

module.exports = {
    app,
    client
}