const timestampStartDefault = Date.now();
const { client } = require("../app")
const fs = require("node:fs")
let sixHoursAgo = Date.now() + (1 * 6 * 60 * 60 * 1000)

/**
 * Get current RPC state fro rpcState.json file on the source code root.
 * @returns {object} data - Parsed JSON object
 */
function getState () {
    data = fs.readFileSync('rpcState.json', 'utf-8', (err, data) => {
        if (err) {
            return "{}";
        }

        return JSON.parse(data)
    })
    return JSON.parse(data)
}

function updateState (data) {
    client.request('SET_ACTIVITY', { pid: process.pid, activity: data })
    const stringifiedJson = Buffer.from(JSON.stringify(data))
    fs.writeFile("rpcState.json", stringifiedJson, (err) => {
        if (err) {
            console.log("warn: State file doesn't exist yet.")
        }
    })
}
function timestampStart() {
    try {
        if (getState() == {} || getState().timestamps.start === undefined) {
            return timestampStartDefault
        } else if (getState().timestamps.start !== undefined ) {
            if (sixHoursAgo > getState().timestamps.start) {
                return getState().timestamps.start
            } else if (sixHoursAgo < getState().timestamps.start) {
                return timestampStartDefault
            } 
        }
    } catch {
        return timestampStartDefault
    }
}



module.exports = {
    timestampStart,
    updateState,
    getState,
    sixHoursAgo
}