#include <stdio.h>
#include <stdlib.h>

#include "client_fds.h"

#define INIT_SIZE 1

void init_clients(client_fds *c)
{
    c->fd = NULL;
    c->id = NULL;
    c->size = 0;
    c->capacity = 0;
}

void client_push_back(client_fds *c, INT32S fd, INT32U id)
{
    if (c->size == c->capacity) 
	{
        c->capacity = c->capacity == 0 ? INIT_SIZE : c->capacity + 4;
        c->fd = realloc(c->fd, c->capacity * sizeof(INT32S));
        c->id = realloc(c->id, c->capacity * sizeof(INT32U));
    }
    c->fd[c->size] = fd;
    c->id[c->size] = id;
    
    c->size += 1;
}


int delete_client(client_fds *c, int index)
{
	if (index < 0 || index >= c->size)
    {
		return -1;
    } 
	memmove(c->fd + index, c->fd + index + 1,
                      (c->size - index - 1) * sizeof(INT32S));

	memmove(c->id + index, c->id + index + 1,
                      (c->size - index - 1) * sizeof(INT32S));
    c->size --;
    
    return 0;

}


int get_client_fd (client_fds *c, int index)
{
    if (index >= c->size)
    {
        fprintf(stderr, "Cients index out of bounds\n");
        return -1;
    }
    return c->fd[index];
}

int get_client_id(client_fds *c, int index) 
{
    if (index >= c->size)
    {
        fprintf(stderr, "Cients index out of bounds\n");
        return -1;
    }
    return c->id[index];
}

void free_clients(client_fds *c) {
    if (c->fd)
	{
      free(c->fd);
	  c->fd = NULL;
    }
    if (c->id)
	{ 
		free(c->id);
		c->id = NULL;
    }
    c->size = 0;
    c->capacity = 0;
}


