// @ts-ignore
import { DiscordRPCClient } from "@ryuziii/discord-rpc";

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

type RPCMode = "watching" | "reading" | string;

interface RPCData {
    details?: string;
    state?: string;
    mode?: RPCMode;
    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 (e) {}
        rpcClient = null;
    }
    if (reconnectTimer) {
        clearTimeout(reconnectTimer);
        reconnectTimer = null;
    }

    console.log(`Discord RPC: Starting with id ...${clientId.slice(-4)}`);

    try {

        rpcClient = new DiscordRPCClient({
            clientId: clientId,
            transport: 'ipc'
        });
    } catch (err) {
        console.error('Discord RPC:', err);
        return;
    }

    rpcClient.on("ready", () => {
        connected = true;
        const user = rpcClient?.user ? rpcClient.user.username : 'User';
        console.log(`Discord RPC: Authenticated for: ${user}`);

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

    rpcClient.on('disconnected', () => {
        console.log('Discord RPC: Desconexión detectada.');
        attemptReconnect(clientId);
    });

    rpcClient.on('error', (err: { message: any; }) => {
        console.error('[Discord RPC] Error:', err.message);

        if (connected) {
            attemptReconnect(clientId);
        }
    });

    try {
        rpcClient.connect().catch((err: { message: any; }) => {
            console.error('Discord RPC: Error al conectar', err.message);

            attemptReconnect(clientId);
        });
    } catch (err) {
        console.error('Discord RPC: Error al iniciar la conexión', err);
        attemptReconnect(clientId);
    }
}

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

    let type;
    let state = data.state;
    let details = data.details;

    if (data.mode === "watching") {
        type = 3
    } else if (data.mode === "reading") {
        type = 0
    } else {
        type = 0
    }


    try {
        rpcClient.setActivity({
            details: details,
            state: state,
            type: type,
            startTimestamp: new Date(),
            largeImageKey: "bigpicture",
            largeImageText: "v2.0.0",
            instance: false
        });
    } catch (error) {
        console.error("Discord RPC: Failed to set activity", error);
    }
}