/* 
 * Neighbours Layer
 * 
 * neighbours.c
 *
 * Neighbours related functions.
 * 
 */

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

#include <config.h>
#include <servers.h>
#include "neighbours.h"


/*
 * neighbours_filename: the file name with the neighbours data
 */
static char neighbours_filename[MAX_FILENAME_SIZE];


int neighbours_new(char *filename, char *servers) {
	FILE *fp = NULL;
	
	strncpy(neighbours_filename, filename, MAX_FILENAME_SIZE - 1);
	
	fp = fopen(neighbours_filename, "r");

	if (fp == NULL) {
		return -1;
	}
	
	fclose(fp);
	
	if (servers_new(servers, 1) != 0) {
		return -1;
	}
	
	printf("\33[1m[neighbours_new]\33[0m '%s' loaded.\n", filename);
	return 0;
}


void neighbours_get(char* neighbours) {
	FILE *fp;
	int weight;
	char counter[MAX_COUNTER_SIZE];
	char address[MAX_ADDRESS_SIZE];
	int port;
	char aux[MAX_NEIGHBOURS_SIZE];
	char buffer[1024];
	char *ptr;
	
	fp = fopen (neighbours_filename, "r");
	
	if (fp == NULL) {
		printf("\33[1m[neighbours_get]\33[0m Neighbours data not found!\n");
		exit(-1);
	}
	
	memset(aux, 0, MAX_NEIGHBOURS_SIZE);
	while(fgets(aux, MAX_NEIGHBOURS_SIZE, fp) != NULL) {
		sscanf(aux, "%s", counter);
		if(strcmp(counter, SERVER_ID) == 0) {
			break;
		}
	}
					
	ptr = aux + strlen(counter);
	neighbours[0] = '\0';
	
	while (*ptr != '\n' && *ptr != '\0') {
		// moves the ptr to the next pair (counter, weight)
		ptr++;

		sscanf(ptr, "%s %d", counter, &weight);
		servers_get(counter, address, &port);
		strcat(neighbours, address);
		strcat(neighbours, ":");
		sprintf(buffer, "%d", port);
		strcat(neighbours, buffer);
		strcat(neighbours, "/");
		sprintf(buffer, "%d", weight);
		strcat(neighbours, buffer);
		strcat(neighbours, " ");
		
		// moves the ptr to the end of the pair (counter, weight)
		ptr += strlen(counter) + strlen(buffer) + 1;
	}
	
	neighbours[strlen(neighbours) - 1] = '\0';

	fclose(fp);
}
