#include "entry.h"
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

void os_entries_init(os_entries_t* os)
{ 
	int i;
	os->n=0;
	for(i=0; i<16; i++)
	{
		strcpy(os->entries[i].name, "");
		strcpy(os->entries[i].location, "");
		strcpy(os->entries[i].kernel, "");
		strcpy(os->entries[i].initrd, "");
		strcpy(os->entries[i].rootfs, "");
		strcpy(os->entries[i].append, "");
	}
}


 
void os_entries_add(os_entries_t* os, json_object* obj)
{
	printf("New\n");
	json_object_object_foreach(obj, key, val)
	{
		printf("  %s\n", key);
		if(!strcmp(key, "name")) strcpy(os->entries[os->n].name, json_object_get_string(val));
		if(!strcmp(key, "location")) strcpy(os->entries[os->n].location, json_object_get_string(val));
		if(!strcmp(key, "kernel")) strcpy(os->entries[os->n].kernel, json_object_get_string(val));
		if(!strcmp(key, "rootfs")) strcpy(os->entries[os->n].rootfs, json_object_get_string(val));
		if(!strcmp(key, "initrd")) strcpy(os->entries[os->n].initrd, json_object_get_string(val));
		if(!strcmp(key, "append")) strcpy(os->entries[os->n].append, json_object_get_string(val));
	}
	if(strlen(os->entries[os->n].name) && strlen(os->entries[os->n].location) &&
			strlen(os->entries[os->n].kernel) && strlen(os->entries[os->n].rootfs))
			os->n++;
}


int os_entries_parse(os_entries_t* os, const char* file)
{
	int n,i=0;
	json_object* obj = json_object_from_file(file), *iter;
	if(!obj)
	{
		fprintf(stderr, "Error bad file (%s)\n", file);
		return -1;
	}
	json_object_object_get_ex(obj, "list", &iter);
	n=json_object_array_length(iter);
	for(i=0; i<n; i++)
	{
		os_entries_add(os, json_object_array_get_idx(iter,i));
	}
	
	json_object_put(obj);
	return 0;
}
