/*
 * response_list.c
 *
 * Implementation of list manipulation functions
 * 
 */


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


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


void res_lst_destroy(res_list_t *list)
{
	if (list == NULL) {
		return;
	}
	
	res_lst_iitem_t *el, *next;
	
	el = list->first;
	
	while (el != NULL) {
		next = el->next;
		
		if (el->response.res->type == REQ_TAKE &&
		    el->response.res->body.take.cover != NULL) {
			free(el->response.res->body.take.cover);
		}
		
		free(el->response.res);
		free(el);
		el = next;
	}
	
	free(list);
}


void res_lst_insert(res_list_t *list, response_t *response)
{
	if (list == NULL || response == NULL) {
		return;
	}

	res_lst_iitem_t *new_element;
	new_element = (res_lst_iitem_t*) malloc(sizeof(res_lst_iitem_t));
	new_element->response.res = response->res;
	new_element->response.ressz = response->ressz;
	new_element->next = NULL;
	
	if (list->first == NULL) {
    	list->first = new_element;
		list->last = new_element;
	} else {
		list->last->next = new_element;
		list->last = new_element;
   	}
}


void res_lst_print(res_list_t *list)
{
	int i = 1;
	res_lst_iitem_t *el;
	
	el = list->first;
	
	while(el != NULL) {
		printf("%2d: res:%d, ressz: %d.\n", i, el->response.res->type, el->response.ressz);
		el = el->next;
		++i;
	}
}


response_t* res_lst_pop(res_list_t *list)
{
	response_t* res;
	res_lst_iitem_t *el;
	
	if(list == NULL || list->first == NULL) {
		return NULL;
	}
	
	el = list->first;
	
	res = (response_t*) malloc(sizeof(response_t) + (sizeof(char) * el->response.res->body.take.size));
	
	*res = el->response;
	list->first = el->next;

	free(el);
	
	return res;
}
