/**
 * Copyright (c) 2025 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#pragma once
#include "error/error.h"
#include <arpa/inet.h>
#include "packet/packet.h"

typedef struct client_s client_t;
typedef struct clientconnect_s clientconnect_t;

typedef struct {
  uint16_t port;
} networkedclientconnect_t;

typedef struct {
  int32_t socket;
  struct sockaddr_in address;
  pthread_t thread;
  pthread_mutex_t lock;
  pthread_cond_t cond;
} networkedclient_t;

/**
 * Connects to a networked server.
 * 
 * @param client Pointer to the client structure.
 * @param connect Connection information.
 */
errorret_t networkedClientConnect(
  client_t *client,
  const networkedclientconnect_t connect
);

/**
 * Closes the connection to a networked server.
 * 
 * @param client Pointer to the client structure.
 */
void networkedClientDisconnect(client_t *client);

/**
 * Writes data to the networked server.
 * 
 * @param client Pointer to the client structure.
 * @param data Data to write.
 * @param len Length of the data.
 * @return Error code.
 */
errorret_t networkedClientWrite(
  const client_t *client,
  const uint8_t *data,
  const size_t len
);

/**
 * Writes a packet to the networked server.
 * 
 * @param client Pointer to the client structure.
 * @param packet Pointer to the packet structure.
 * @return Error code.
 */
errorret_t networkedClientWritePacket(
  const client_t *client,
  const packet_t *packet
);

/**
 * Reads a packet from the networked server.
 * 
 * @param client Pointer to the client structure.
 * @param packet Pointer to the packet structure to read into.
 * @return Error code.
 */
errorret_t networkedClientReadPacket(const client_t *client, packet_t *packet);

/**
 * Thread function for handling networked client connections.
 * 
 * @param arg Pointer to the client structure.
 * @return NULL.
 */
void * networkedClientThread(void *arg);