# API Documentation

This document provides comprehensive API documentation for the Network Chat Client project.

## Project Information

- **Author**: Molla Samser (Founder, RSK World)
- **Designer & Tester**: Rima Khatun
- **Website**: https://rskworld.in
- **Email**: info@rskworld.com, support@rskworld.com
- **Phone**: +91 93305 39277
- **Year**: 2026
- **License**: MIT

## Table of Contents

1. [Core Classes](#core-classes)
2. [Utility Classes](#utility-classes)
3. [Message Queue System](#message-queue-system)
4. [Data Structures](#data-structures)
5. [Enums and Constants](#enums-and-constants)
6. [Error Handling](#error-handling)
7. [Examples](#examples)

## Core Classes

### ChatClient

The main client class for the chat application.

#### Public Methods

##### Constructor and Destructor

```cpp
ChatClient();
~ChatClient();
```

**Description**: Creates and destroys a chat client instance.

##### Initialization

```cpp
bool initialize();
```

**Description**: Initializes the chat client, sets up Winsock, and prepares encryption.

**Returns**: `true` if initialization successful, `false` otherwise.

**Example**:
```cpp
ChatClient client;
if (!client.initialize()) {
    std::cerr << "Failed to initialize client" << std::endl;
    return 1;
}
```

##### Connection Management

```cpp
bool start(const std::string& serverIP = SERVER_IP, int port = DEFAULT_PORT);
```

**Description**: Connects to the chat server and starts communication threads.

**Parameters**:
- `serverIP` (string): IP address of the server (default: "127.0.0.1")
- `port` (int): Port number of the server (default: 54000)

**Returns**: `true` if connection successful, `false` otherwise.

```cpp
void stop();
```

**Description**: Stops the client, disconnects from server, and cleans up resources.

```cpp
void run();
```

**Description**: Main client loop for handling user input and commands.

##### Message Operations

```cpp
void sendMessage(const std::string& content, const std::string& receiver = "");
```

**Description**: Sends a message to the server.

**Parameters**:
- `content` (string): Message content
- `receiver` (string): Recipient username (empty for broadcast)

```cpp
void sendBroadcast(const std::string& content);
```

**Description**: Sends a broadcast message to all connected users.

**Parameters**:
- `content` (string): Message content

```cpp
void sendPrivateMessage(const std::string& receiver, const std::string& content);
```

**Description**: Sends a private message to a specific user.

**Parameters**:
- `receiver` (string): Recipient username
- `content` (string): Message content

##### Utility Methods

```cpp
void displayHelp();
```

**Description**: Displays available commands and usage information.

```cpp
void displayMessageHistory();
```

**Description**: Shows the message history for the current session.

```cpp
void clearScreen();
```

**Description**: Clears the console screen.

```cpp
bool isConnectedToServer() const;
```

**Returns**: `true` if connected to server, `false` otherwise.

```cpp
std::string getUsername() const;
```

**Returns**: Current username.

```cpp
std::vector<Message> getMessageHistory() const;
```

**Returns**: Vector of messages in the history.

---

### ChatServer

The main server class for the chat application.

#### Public Methods

##### Constructor and Destructor

```cpp
ChatServer();
~ChatServer();
```

##### Initialization

```cpp
bool initialize(int port = DEFAULT_PORT);
```

**Description**: Initializes the server with specified port.

**Parameters**:
- `port` (int): Port number to listen on (default: 54000)

**Returns**: `true` if initialization successful, `false` otherwise.

```cpp
bool start();
```

**Description**: Starts the server and begins listening for connections.

**Returns**: `true` if server started successfully, `false` otherwise.

```cpp
void stop();
```

**Description**: Stops the server and cleans up all connections.

```cpp
void run();
```

**Description**: Main server loop for handling administrative commands.

##### Client Management

```cpp
int getConnectedClientsCount() const;
```

**Returns**: Number of connected clients.

```cpp
int getAuthenticatedClientsCount() const;
```

**Returns**: Number of authenticated clients.

```cpp
std::vector<std::string> getOnlineUsers();
```

**Returns**: Vector of online usernames.

##### Administrative Functions

```cpp
void kickClient(const std::string& username);
```

**Description**: Kicks a client from the server.

**Parameters**:
- `username` (string): Username to kick

```cpp
void broadcastServerMessage(const std::string& message);
```

**Description**: Broadcasts a server message to all clients.

**Parameters**:
- `message` (string): Server message

```cpp
void displayServerStats();
```

**Description**: Displays server statistics and online users.

```cpp
void displayMessageHistory();
```

**Description**: Shows the server's message history.

##### Utility Methods

```cpp
bool isServerRunning() const;
```

**Returns**: `true` if server is running, `false` otherwise.

```cpp
std::vector<ServerMessage> getMessageHistory() const;
```

**Returns**: Vector of server messages.

---

## Utility Classes

### StringUtils

String manipulation utilities.

#### Static Methods

```cpp
static std::vector<std::string> split(const std::string& str, char delimiter);
```

**Description**: Splits a string by delimiter.

```cpp
static std::string join(const std::vector<std::string>& strings, const std::string& delimiter);
```

**Description**: Joins vector of strings with delimiter.

```cpp
static std::string trim(const std::string& str);
```

**Description**: Trims whitespace from string.

```cpp
static std::string toLower(const std::string& str);
```

**Description**: Converts string to lowercase.

```cpp
static std::string toUpper(const std::string& str);
```

**Description**: Converts string to uppercase.

```cpp
static bool isAlphanumeric(const std::string& str);
```

**Description**: Checks if string contains only alphanumeric characters.

```cpp
static bool validateUsername(const std::string& username);
```

**Description**: Validates username format.

```cpp
static bool validateEmail(const std::string& email);
```

**Description**: Validates email format.

---

### TimeUtils

Time and date utilities.

#### Static Methods

```cpp
static std::string getCurrentTimestamp(const std::string& format = "%Y-%m-%d %H:%M:%S");
```

**Description**: Gets current timestamp as formatted string.

```cpp
static std::string getCurrentDate();
```

**Description**: Gets current date in YYYY-MM-DD format.

```cpp
static std::string getCurrentTime();
```

**Description**: Gets current time in HH:MM:SS format.

```cpp
static std::string formatDuration(long seconds);
```

**Description**: Formats duration in human readable form.

---

### CryptoUtils

Encryption and security utilities.

#### Static Methods

```cpp
static std::string generateRandomString(size_t length);
```

**Description**: Generates random string of specified length.

```cpp
static std::string generateMD5(const std::string& input);
```

**Description**: Generates MD5 hash of input string.

```cpp
static std::string generateSHA256(const std::string& input);
```

**Description**: Generates SHA256 hash of input string.

```cpp
static std::string xorEncrypt(const std::string& data, const std::string& key);
```

**Description**: XOR encrypts data with key.

```cpp
static std::string xorDecrypt(const std::string& encryptedData, const std::string& key);
```

**Description**: XOR decrypts data with key.

```cpp
static std::string base64Encode(const std::string& data);
```

**Description**: Base64 encodes data.

```cpp
static std::string base64Decode(const std::string& encodedData);
```

**Description**: Base64 decodes data.

---

### Logger

Logging utility for debug and monitoring.

#### Static Methods

```cpp
static void setLogLevel(LogLevel level);
```

**Description**: Sets minimum log level.

```cpp
static void setLogFile(const std::string& filename);
```

**Description**: Sets log file path.

```cpp
static void debug(const std::string& message, const std::string& tag = "");
```

**Description**: Logs debug message.

```cpp
static void info(const std::string& message, const std::string& tag = "");
```

**Description**: Logs info message.

```cpp
static void warning(const std::string& message, const std::string& tag = "");
```

**Description**: Logs warning message.

```cpp
static void error(const std::string& message, const std::string& tag = "");
```

**Description**: Logs error message.

```cpp
static void critical(const std::string& message, const std::string& tag = "");
```

**Description**: Logs critical message.

---

### ConfigManager

Configuration management utilities.

#### Static Methods

```cpp
static bool loadConfig(const std::string& filename);
```

**Description**: Loads configuration from file.

```cpp
static bool saveConfig(const std::string& filename);
```

**Description**: Saves configuration to file.

```cpp
static std::string getString(const std::string& key, const std::string& defaultValue = "");
```

**Description**: Gets string configuration value.

```cpp
static int getInt(const std::string& key, int defaultValue = 0);
```

**Description**: Gets integer configuration value.

```cpp
static bool getBool(const std::string& key, bool defaultValue = false);
```

**Description**: Gets boolean configuration value.

```cpp
static void setString(const std::string& key, const std::string& value);
```

**Description**: Sets string configuration value.

```cpp
static void setInt(const std::string& key, int value);
```

**Description**: Sets integer configuration value.

```cpp
static void setBool(const std::string& key, bool value);
```

**Description**: Sets boolean configuration value.

---

## Message Queue System

### MessageQueue

Thread-safe priority queue for messages.

#### Public Methods

```cpp
explicit MessageQueue(size_t maxQueueSize = 1000);
```

**Description**: Constructor with maximum queue size.

```cpp
bool push(const QueueMessage& message);
```

**Description**: Pushes message to queue.

```cpp
QueueMessage pop();
```

**Description**: Pops message from queue (blocking).

```cpp
bool tryPop(QueueMessage& message);
```

**Description**: Tries to pop message (non-blocking).

```cpp
size_t size() const;
```

**Description**: Gets current queue size.

```cpp
bool empty() const;
```

**Description**: Checks if queue is empty.

```cpp
void clear();
```

**Description**: Clears all messages from queue.

```cpp
void shutdownQueue();
```

**Description**: Shuts down queue and wakes up waiting threads.

---

### MessageQueueManager

Manages multiple message queues.

#### Public Methods

```cpp
std::shared_ptr<MessageQueue> getQueue(const std::string& name, size_t maxSize = 1000);
```

**Description**: Gets or creates a message queue.

```cpp
bool removeQueue(const std::string& name);
```

**Description**: Removes a message queue.

```cpp
std::vector<std::string> getQueueNames() const;
```

**Description**: Gets all queue names.

```cpp
std::map<std::string, std::pair<size_t, size_t>> getAllQueueStats() const;
```

**Description**: Gets statistics for all queues.

---

### MessageRouter

Routes messages to appropriate queues.

#### Public Methods

```cpp
void addRoutingRule(const std::string& pattern, const std::string& queueName);
```

**Description**: Adds routing rule based on regex pattern.

```cpp
bool routeMessage(const QueueMessage& message);
```

**Description**: Routes message to appropriate queue.

```cpp
std::map<std::string, std::string> getRoutingRules() const;
```

**Description**: Gets all routing rules.

---

## Data Structures

### Message

Structure for chat messages.

```cpp
struct Message {
    MessageType type;
    std::string sender;
    std::string receiver;
    std::string content;
    std::string timestamp;
};
```

### QueueMessage

Structure for queued messages.

```cpp
struct QueueMessage {
    std::string id;
    std::string content;
    std::string sender;
    std::string receiver;
    std::string timestamp;
    int priority;
    MessageType type;
};
```

### ClientInfo

Structure for client information.

```cpp
struct ClientInfo {
    SOCKET socket;
    std::string username;
    std::string ipAddress;
    ClientStatus status;
    std::thread clientThread;
    std::string sessionKey;
    std::chrono::steady_clock::time_point lastActivity;
};
```

### ServerMessage

Structure for server messages.

```cpp
struct ServerMessage {
    std::string sender;
    std::string receiver;
    std::string content;
    std::string timestamp;
    bool isPrivate;
};
```

---

## Enums and Constants

### MessageType

Enum for message types.

```cpp
enum class MessageType {
    AUTH,
    MESSAGE,
    BROADCAST,
    PRIVATE,
    DISCONNECT,
    ERROR
};
```

### ClientStatus

Enum for client status.

```cpp
enum class ClientStatus {
    CONNECTED,
    AUTHENTICATED,
    DISCONNECTED
};
```

### Constants

```cpp
#define MAX_BUFFER_SIZE 4096
#define DEFAULT_PORT 54000
#define SERVER_IP "127.0.0.1"
#define MAX_CLIENTS 100
```

---

## Error Handling

### Error Codes

The API uses return values and exceptions for error handling:

- **Return Values**: Most methods return `bool` for success/failure
- **Exceptions**: Critical errors throw `std::exception`
- **Logging**: Errors are logged using the Logger class

### Common Error Scenarios

1. **Connection Errors**
   - Server not running
   - Network unreachable
   - Port already in use

2. **Authentication Errors**
   - Invalid username
   - Duplicate username
   - Network issues during auth

3. **Message Errors**
   - Message too long
   - Invalid recipient
   - Network transmission errors

### Error Handling Example

```cpp
try {
    ChatClient client;
    if (!client.initialize()) {
        Logger::error("Failed to initialize client");
        return 1;
    }
    
    if (!client.start("127.0.0.1", 54000)) {
        Logger::error("Failed to connect to server");
        return 1;
    }
    
    client.run();
    
} catch (const std::exception& e) {
    Logger::critical("Fatal error: " + std::string(e.what()));
    return 1;
}
```

---

## Examples

### Basic Client Usage

```cpp
#include "chat_client.h"

int main() {
    ChatClient client;
    
    // Initialize client
    if (!client.initialize()) {
        std::cerr << "Failed to initialize client" << std::endl;
        return 1;
    }
    
    // Connect to server
    if (!client.start("127.0.0.1", 54000)) {
        std::cerr << "Failed to connect to server" << std::endl;
        return 1;
    }
    
    // Run client
    client.run();
    
    return 0;
}
```

### Basic Server Usage

```cpp
#include "chat_server.h"

int main() {
    ChatServer server;
    
    // Initialize server
    if (!server.initialize(54000)) {
        std::cerr << "Failed to initialize server" << std::endl;
        return 1;
    }
    
    // Start server
    if (!server.start()) {
        std::cerr << "Failed to start server" << std::endl;
        return 1;
    }
    
    // Run server
    server.run();
    
    return 0;
}
```

### Utility Usage

```cpp
#include "utils.h"

int main() {
    // String utilities
    std::vector<std::string> parts = StringUtils::split("hello,world,test", ',');
    std::string joined = StringUtils::join(parts, " ");
    
    // Time utilities
    std::string timestamp = TimeUtils::getCurrentTimestamp();
    
    // Crypto utilities
    std::string encrypted = CryptoUtils::xorEncrypt("secret", "key");
    std::string decrypted = CryptoUtils::xorDecrypt(encrypted, "key");
    
    // Logging
    Logger::info("Application started", "Main");
    Logger::error("Something went wrong", "Main");
    
    return 0;
}
```

### Message Queue Usage

```cpp
#include "message_queue.h"

int main() {
    auto queueManager = std::make_shared<MessageQueueManager>();
    auto queue = queueManager->getQueue("test", 100);
    
    // Add messages
    QueueMessage msg1("Hello", "user1", "", 5);
    QueueMessage msg2("World", "user2", "", 10);
    
    queue->push(msg1);
    queue->push(msg2);
    
    // Process messages
    while (!queue->empty()) {
        QueueMessage msg = queue->pop();
        std::cout << "Processing: " << msg.content << std::endl;
    }
    
    return 0;
}
```

---

## Contact Information

**API Documentation Questions:**
- **Email**: info@rskworld.com, support@rskworld.com
- **Phone**: +91 93305 39277
- **Website**: https://rskworld.in
- **Address**: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147

---

© 2026 RSK World. All rights reserved.

*Content used for educational purposes only. View Disclaimer: https://rskworld.in/disclaimer.php*
