//
//parse.c
//
//Functions relevant to reading and parsing configuration style files.
//
//
//-UserX 2001/11/04


#include <stdio.h>
#include <string.h>
#include "base/parse.h"
#include "base/strarray.h"
#include "base/str.h"
#include "base/strio.h"
#include "base/logger.h"
#include "file/file.h"

char whitespace[] = " \t";


//reads a file stream and parses it into string pairs.
//lines starting with a # or ; are discarded
//leading and traing whitespace is trimmed from the string pairs
//string pairs are read in the form of:
// "[<ws>]<key>[<ws>]=[<ws>]<val>[<ws>]" 
// <key> - must be at least one char long
// [<ws>] = optional whitespace.
//any line without an "=" symbol are discard
StringPairArrayHandle *spaReadFileStream(FileHandle *fh){
	int i;
	//StringPairArrayHandle *array = makeStringPairArray();
	StringPairArrayHandle *array = spaMake();
	char *s;
	char *cp;
	StringPair sp;

	if(fh == NULL) {
		return array;
	}
	
	while(!fileEOF(fh) && !fileError(fh)) {
		s = stringTrim(stringReadLine(fh), whitespace);
		LOGDEBUGSPAM(stringCopyMany("spaReadFileStream: readline:", s, NULL));
		switch(s[0]) {
		case ';':
		case '#':
			break;
		default:
			cp = strchr(s, '=');
			if(cp != NULL) {
				i = cp - s;
				if(i > 0) {
					sp.key = stringTrim(stringCopyPart(s, 0, i), whitespace);
					sp.val = stringTrim(stringCopy(cp + 1), whitespace);
					spaAppend(array, sp);
				}
			}
		}
		stringFree(s);
	}
	return array;
}

//open filename for reading then calls: spaReadFile
StringPairArrayHandle *spaReadFile(char *filename){
	FileHandle *fh;
	StringPairArrayHandle *array;
	if(filename == NULL) {
		//return makeStringPairArray();
		return spaMake();
	}
	fh = fileOpen(filename, "r");
	if(fh == NULL) {
		//return makeStringPairArray();
		return NULL;//spaMake();
	}
	array = spaReadFileStream(fh);
	fileClose(fh);
	return array;
}


//writes a string pairs to a file
//string pairs are written in the form of:
// "<key> = <val>"
void spaWriteFileStream(StringPairArrayHandle *array, FileHandle *fh){
	int i;
	if(fh == NULL) {
		return;
	}
	for(i = 0; i < array->size; i++){
		fileWriteString(fh,
				stringCopyMany(array->data[i].key, " = ", array->data[i].val, "\n", NULL)
			);
	}
}

//opens a file for write then calls spaWriteFileStream
void spaWriteFile(StringPairArrayHandle *array, char *filename){
	FileHandle *fh;
	if(filename == NULL) {
		return;
	}
	fh = fileOpen(filename, "w");
	if(fh == NULL) {
		return;
	}
	spaWriteFileStream(array, fh);
	fileClose(fh);
}

