/**************************************************************************/
/*  discord_rpc.h                                                         */
/**************************************************************************/
/*                     AeThex Engine - Discord Rich Presence              */
/*                                                                        */
/*  Provides Discord Rich Presence integration for games and the editor   */
/**************************************************************************/

#ifndef DISCORD_RPC_H
#define DISCORD_RPC_H

#include "core/object/ref_counted.h"
#include "core/os/thread.h"
#include "core/os/mutex.h"

class DiscordRPC : public RefCounted {
	GDCLASS(DiscordRPC, RefCounted);

public:
	enum ConnectionState {
		DISCONNECTED,
		CONNECTING,
		CONNECTED,
		DISCONNECTING,
	};

private:
	static DiscordRPC *singleton;
	
	String application_id;
	ConnectionState state = DISCONNECTED;
	
	// Presence data
	String details;
	String state_text;
	String large_image_key;
	String large_image_text;
	String small_image_key;
	String small_image_text;
	int64_t start_timestamp = 0;
	int64_t end_timestamp = 0;
	int party_size = 0;
	int party_max = 0;
	String party_id;
	String match_secret;
	String join_secret;
	String spectate_secret;
	
	// IPC connection
	int pipe_fd = -1;
	bool running = false;
	Thread *thread = nullptr;
	Mutex mutex;
	
	// Platform-specific connection
	bool _connect_pipe();
	void _disconnect_pipe();
	bool _write_frame(int opcode, const String &payload);
	String _read_frame();
	void _thread_func();
	static void _thread_wrapper(void *userdata);
	
	// JSON helpers
	String _build_handshake();
	String _build_presence_payload();

protected:
	static void _bind_methods();

public:
	static DiscordRPC *get_singleton();
	
	// Initialization
	void initialize(const String &p_app_id);
	void shutdown();
	bool is_connected() const;
	ConnectionState get_state() const;
	
	// Presence setters
	void set_details(const String &p_details);
	String get_details() const;
	
	void set_state(const String &p_state);
	String get_state_text() const;
	
	void set_large_image(const String &p_key, const String &p_text = "");
	void set_small_image(const String &p_key, const String &p_text = "");
	
	void set_timestamps(int64_t p_start = 0, int64_t p_end = 0);
	void set_party(const String &p_id, int p_size, int p_max);
	
	void set_secrets(const String &p_match = "", const String &p_join = "", const String &p_spectate = "");
	
	// Update presence
	void update_presence();
	void clear_presence();
	
	// Editor-specific
	void set_editor_presence(const String &p_project_name, const String &p_scene_name = "");
	void set_game_presence(const String &p_game_name, const String &p_activity = "");
	
	DiscordRPC();
	~DiscordRPC();
};

VARIANT_ENUM_CAST(DiscordRPC::ConnectionState);

#endif // DISCORD_RPC_H
