#include "configutil.h"

configutil::configutil(xutil *xu) {

	char	*filename=new char[1024];
	sprintf(filename,"%s/.asfaces",getenv("HOME"));

	first=NULL;
	last=NULL;
	current=NULL;

	firstpix=NULL;
	lastpix=NULL;
	currentpix=NULL;

	xutility=xu;

	FILE	*configfile;
	
	configfile=fopen(filename,"r");
	delete[] filename;

	if (configfile!=NULL) {
		char 	*email=new char[80];
		char 	*pixfile=new char[80];

		fscanf(configfile,"%s%s",email,pixfile);
		while(!feof(configfile)) {
			if (first==NULL) {
				first=new confignode(email, 
							HandlePixmap(pixfile),
							NULL, NULL);
				current=first;
			} else {
				current=last;
				current->next=new confignode(email, 
							HandlePixmap(pixfile),
							last, NULL);
				current=current->next;
			}
			last=current;
			fscanf(configfile,"%s%s",email,pixfile);
		}

		fclose(configfile);
	}
}

configutil::~configutil() {
	current=first;
	while (current!=last) {
		current=current->next;
		delete current->previous;
	}
	delete last;
	currentpix=firstpix;
	while (currentpix!=lastpix) {
		currentpix=currentpix->next;
		delete currentpix->previous;
	}
	delete lastpix;
}

Pixmap	*configutil::HandlePixmap(char *file) {

	currentpix=firstpix;
	if (currentpix==NULL) {
		currentpix=new pixmapnode(file, xutility, NULL, NULL);
		firstpix=currentpix;
		lastpix=currentpix;
		return &currentpix->pixmap;
	} else {
		while (currentpix!=lastpix) {
			currentpix=currentpix->next;
			if (!strcmp(currentpix->file, file)) {	
				return &currentpix->pixmap;
			}
		}
	
		currentpix->next=new pixmapnode(file, xutility,
							currentpix, NULL);
		currentpix=currentpix->next;
		lastpix=currentpix;
		return &currentpix->pixmap;
	}
}
