import { Client } from "@xhayper/discord-rpc";

let rpcClient: Client | null = null;
let reconnectTimer: NodeJS.Timeout | null = null;
let connected = false;

interface RPCData {
    details?: string;
    state?: string;
    mode?: string;
    startTimestamp?: number;
    endTimestamp?: number;
    paused?: boolean;
    version?: string;
}

function attemptReconnect(clientId: string) {
    connected = false;

    if (reconnectTimer) {
        clearTimeout(reconnectTimer);
        reconnectTimer = null;
    }

    console.log('Discord RPC: Trying to reconnect...');

    reconnectTimer = setTimeout(() => {
        initRPC(clientId);
    }, 10000);
}

export function initRPC(clientId: string) {
    if (rpcClient) {
        try { rpcClient.destroy(); } catch {}
        rpcClient = null;
    }

    if (reconnectTimer) {
        clearTimeout(reconnectTimer);
        reconnectTimer = null;
    }

    rpcClient = new Client({ clientId });

    rpcClient.on("ready", () => {
        connected = true;
        console.log("Discord RPC conectado");

        setTimeout(() => {
            setActivity({ details: "Browsing", state: "In App" });
        }, 1000);
    });

    rpcClient.on("disconnected", () => {
        connected = false;
        attemptReconnect(clientId);
    });

    rpcClient.on("error", () => {
        if (connected) attemptReconnect(clientId);
    });

    rpcClient.login().catch(() => {
        attemptReconnect(clientId);
    });
}

export function setActivity(data: RPCData = {}) {
    if (!rpcClient || !connected) return;

    let type = 0;
    if (data.mode === "watching") type = 3;
    if (data.mode === "reading") type = 0;

    const activity: any = {
        details: data.details,
        state: data.state,
        type,
        instance: false
    };

    if (data.paused) {
        activity.largeImageText = "⏸  ";
        delete activity.startTimestamp;
        delete activity.endTimestamp;
    } else {
        activity.largeImageKey = "bigpicture";
        activity.largeImageText = data.version ?? "v2.0.0";

        if (data.startTimestamp && data.endTimestamp) {
            activity.startTimestamp = data.startTimestamp;
            activity.endTimestamp = data.endTimestamp;
        }
    }

    rpcClient.user?.setActivity(activity);
}