/*
 * request_list.c - implementation of the requests list functions 
 */


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "request_list.h"

req_list_t* req_lst_new()
{
	req_list_t *list;
	list = (req_list_t*) malloc(sizeof(req_list_t));
	list->first = NULL;
	list->last = NULL;
	return list;
}


void req_lst_destroy(req_list_t *list)
{
	if (list == NULL) {
		return;
	}
	
	req_lst_iitem_t *el, *next;
	
	el = list->first;
	
	while (el != NULL) {
		next = el->next;
		free(el);
		el = next;
	}
	
	free(list);
}


void req_lst_insert(req_list_t *list, char* counter, char* title)
{
	req_lst_iitem_t *element = req_lst_find(list, counter);
	
	if (element != NULL) {
		strcpy(element->titles + strlen(element->titles), " ");
		strncpy(element->titles + strlen(element->titles), title, MAX_BOOKNAME_SIZE + 2);
		return;
	}
	
	element = (req_lst_iitem_t*) malloc(sizeof(req_lst_iitem_t));
	strncpy(element->counter, counter, MAX_COUNTER_ID_SIZE);
	strncpy(element->titles, title, MAX_BOOKNAME_SIZE + 2);
	element->next = NULL;

	if (list->first == NULL) {
    	list->first = element;
		list->last = element;
	} else {
		list->last->next = element;
		list->last = element;
   	}
}


req_lst_iitem_t* req_lst_pop(req_list_t *list)
{
	req_lst_iitem_t *el;
	
	if(list->first == NULL) {
		return NULL;
	}
	
	el = list->first;
	list->first = el->next;

	return el;
}


req_lst_iitem_t* req_lst_find(req_list_t *list, char *counter) {
	
	if (list != NULL && list->first != NULL) {
		req_lst_iitem_t *ptr_itm = list->first;
		
		while (ptr_itm != NULL) {
			if ((strncmp(ptr_itm->counter, counter, strlen(counter)) == 0) ){
				return ptr_itm;
			}
			ptr_itm = ptr_itm->next; 			
		}
	} 

	return NULL;
}

void req_lst_print(req_list_t *list)
{
	int i = 1;
	req_lst_iitem_t *el;
	
	el = list->first;
	
	while(el != NULL) {
		printf("%2d: Counter:[%s] Titles: '%s'.\n", i, el->counter, el->titles);
		el = el->next;
		++i;
	}
}
