#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include "parser.h"

#define YesOrNo() ((strcmp(val, "yes") > 0) ? 1 : 0)

FILE *OpenFile(const char *file, const char *mode) {
	FILE *fp = fopen(file, mode);
	if (fp == NULL)
		fprintf(stderr, "Can not open %s with %s mode\n", file, mode);

	return fp;
}

int ReadCfg(CONFIG *cfg) {
	memset(cfg, 0, sizeof(CONFIG));

	FILE *fp = OpenFile(CONFIG_FILE, "r");
	if (fp == NULL)
		return 1;

	char *str = NULL;
	ssize_t bytes = 0;
	size_t n = 0;

	while ((bytes = getline(&str, &n, fp)) > 0) {
		char *tok_rest = str;
		char *var = strtok_r(tok_rest, " ", &tok_rest);
		char *val = strtok_r(tok_rest, " ", &tok_rest);

		if (var == NULL || val == NULL)
			continue;

		if (var[0] == '#')
			continue;

		else if (!strcmp(var, "fullscreen"))
			cfg->fullscreen = YesOrNo();

		else if (!strcmp(var, "fullscreen_custom"))
			cfg->fullscreen_custom = YesOrNo();

		else if (!strcmp(var, "vsync"))
			cfg->vsync = YesOrNo();

		else if (!strcmp(var, "sound_volume"))
			cfg->sound_volume = atoi(val);

		else if (!strcmp(var, "music_volume"))
			cfg->music_volume = atoi(val);

		else if (!strcmp(var, "screen_h"))
			cfg->screen_h = atoi(val);

		else if (!strcmp(var, "screen_w"))
			cfg->screen_w = atoi(val);

		else if (!strcmp(var, "saved_scene"))
			cfg->saved_scene = atoi(val);
	}

	if (str)
		free(str);

	fclose(fp);
	return 0;
}

int WriteCfg(const CONFIG cfg) {
	FILE *fp = OpenFile(CONFIG_FILE, "w");
	if (fp == NULL)
		return 1;

	fprintf(fp, "fullscreen %s\n", (cfg.fullscreen) ? "yes" : "no");
	fprintf(fp, "fullscreen_custom %s\n", (cfg.fullscreen_custom) ? "yes" : "no");
	fprintf(fp, "vsync %s\n", (cfg.vsync) ? "yes" : "no");
	fprintf(fp, "sound_volume %d\n", cfg.sound_volume);
	fprintf(fp, "music_volume %d\n", cfg.music_volume);
	fprintf(fp, "screen_h %d\n", cfg.screen_h);
	fprintf(fp, "screen_w %d\n", cfg.screen_w);
	fprintf(fp, "saved_scene %d\n", cfg.saved_scene);

	fclose(fp);
	return 0;
}
