#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "lib.h"
#include "lprintf.h"
#include "ufile.h"
#define DMID 23
#include "debug.h"
#ifndef FALSE
#define FALSE 0
#define TRUE (!FALSE)
#endif

#include "defines.h"

Ufile *ufile_read_r(char *fname, char *reason, char *src, int line)
{
	FILE *f;
	Ufile *u;
	char *s;
	char bf[BFSZ];
	char *upto;
	char var[BFSZ];

	f = dfopen(fname,"r",src,line,"ufile");
	u = d_callocid(DMID,1,sizeof(Ufile),src,line);
	u->fname = strdup(fname);
	if (f==NULL) {
		lprintf(reason,100,"Cannot read %s %s",fname,strerror(errno));
		return u;
	}
	for (;!feof(f);) {
		if (fgets(bf,BFSZ-1,f)==NULL) break;
		s = mystrtok(bf," \r\n",&upto);
		if (s==NULL) continue;
		ncpy(var,s,BFSZ-1);
		s = mystrtok(NULL,"\r\n",&upto);
		if (s==NULL) continue;
		pair_add(&u->p,var,s);
	}
	fclose(f);
	return u;
}
Ufile *ufile_new(char *fname)
{
	Ufile *u;
	u = calloc(1,sizeof(Ufile));
	u->fname = strdup(fname);
	return u;
}
char *ufile_get(Ufile *u, char *var)
{
	return pair_find(u->p,var);
}
int ufile_true(Ufile *u, char *var)
{
	if (strcmpnc(pair_find(u->p,var),"true")==0)
        return TRUE;
    else
        return FALSE;
}
int ufile_set(Ufile *u, char *var, char *val)
{
	pair_add(&u->p,var,val);
	return TRUE;
}
int ufile_fname(Ufile *u, char *file){
	if (!u || !file ) return FALSE;
	if (u->fname) free(u->fname);
	u->fname = strdup(file);
	return TRUE;
}
int ufile_write(Ufile *u, char *reason)
{
	Pair *p;
	FILE *f;
	f = fopen(u->fname,"w");
	if (f==NULL) {
		if (errno==ENOENT) lib_create_dir(u->fname,0755);
		f = fopen(u->fname,"w");
		if (f==NULL) {
			lprintf(reason,100,"%s %s",u->fname,strerror(errno));
			return FALSE;
		}
	}
	for (p=u->p; p!=NULL;p=p->next) {
		fprintf(f,"%s %s\n",p->var,p->val);
	}
	fclose(f);
	return TRUE;
}
int ufile_free(Ufile *u)
{
	pair_free(&u->p);
	free(u->fname);
	free(u);
	return TRUE;
}

