/*
 * str_list.c - implementation of the string list functions 
 */


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


str_list_t* str_lst_new() {
	str_list_t *list;
	list = (str_list_t*) malloc(sizeof(str_list_t));
	list->first = NULL;
	return list;
}


void str_lst_destroy(str_list_t *list) {
	str_lst_iitem_t *el, *next;
	
	el = list->first;
	
	while(el != NULL) {
		next = el->next;
		free(el->value);
		free(el);
		el = next;
	}
	
	free(list);
}


void str_lst_insert(str_list_t *list, char *value) {
	str_lst_iitem_t *new, *el; 
	
	new = (str_lst_iitem_t*)malloc(sizeof(str_lst_iitem_t));
	new->value = (char*) malloc((strlen(value) + 1) * sizeof(char));
  	strcpy(new->value, value);
	new->next = NULL;
	
	if (list->first == NULL) {
		list->first = new;
		return;
	}
	
	el = list->first;
	
	while(el->next != NULL) {
		el = el->next;
	}
	
	el->next = new;
}


char *str_lst_remove(str_list_t *list) {
	char *res;
	str_lst_iitem_t *el;
	
	if(list->first == NULL) {
		return NULL;
	}
	
	el = list->first;
	
	res = el->value;
	list->first = el->next;

	free(el);
	
	return res;
}


str_lst_iitem_t* str_lst_find(str_list_t *list, char* item) {
	
	if (list != NULL && list->first != NULL) {
		str_lst_iitem_t *ptr_itm = list->first;
		
		while (ptr_itm != NULL) {
			if ((strncmp(ptr_itm->value, item, strlen(item)) == 0) ){
				return ptr_itm;
			}
			ptr_itm = ptr_itm->next; 			
		}
	} 

	return NULL;
}

str_lst_iitem_t* neighbour_find(str_list_t *list, char *item) {
	
	if (list != NULL && list->first != NULL) {
		str_lst_iitem_t *ptr_itm = list->first;
		
		while (ptr_itm != NULL) {
			char address[64];
			char host_port[64 + 6 + 1];
			int j, port;
			
			// gets address, port
			for (j = 0; ptr_itm->value[j] != ':'; ++j) {
				address[j] = ptr_itm->value[j];
			}
			address[j] = '\0';
			sscanf(ptr_itm->value + j, ":%d", &port);
			sprintf(host_port, "%s:%d", address, port);
			
			if ((strncmp(host_port, item, strlen(item)) == 0) ){
				return ptr_itm;
			}
			ptr_itm = ptr_itm->next; 			
		}
	} 

	return NULL;
}

int str_lst_insert_quit(str_list_t *list) {
	int found_releases = 0;
	
	if (list == NULL || list->first == NULL) {
		return found_releases;
	}
	
	str_lst_iitem_t *ptr_itm = list->first;
	str_lst_iitem_t *last_release = NULL;
	
	while (ptr_itm != NULL) {
		if (strncmp(ptr_itm->value, "Release ", 8) == 0) {
			last_release = ptr_itm;
		}
		ptr_itm = ptr_itm->next; 			
	}
	
	str_lst_iitem_t *new = (str_lst_iitem_t*)malloc(sizeof(str_lst_iitem_t));
	new->value = (char*) malloc(6 * sizeof(char));
  	strcpy(new->value, "Quit\n");
	new->next = NULL;
	
	if (last_release != NULL) {
		found_releases = 1;
		new->next = last_release->next;
		last_release->next = new;
	} else {
		new->next = list->first;
		list->first = new;
	}
	
	return found_releases;
}
