/* Copyright (C) 2007  Mikko Sysikaski <mikko.sysikaski@gmail.com>
 * This program is free software distributed under GNU General Public License
 * version 3 or (at your option) any later version.
 * No warranty of any kind is provided. See the accompanying file COPYING for details.
 */

#include "besttimes.h"
#include <cstdio>
#include <stdint.h>

BestTimes BestTimes::m_instance;

void BestTimes::load(const char* filename)
{
	FILE* f = fopen(filename, "r");
	if (!f) {
		fprintf(stderr, "Warning: couldn't read score file %s\n", filename);
		return;
	}

	char buf[1024];
	uint32_t len;
	BoardTimes tmp;
	while(!feof(f)) {
		fread(&len, 4, 1, f);
		if (feof(f))
			break;
		fread(buf, 1, len, f);
		buf[len] = 0;
		
		int32_t time;
		fread(&time, 4, 1, f);
		int i=0;
		while(time >= 0) {
			if (i >= BoardTimes::TIMES_PER_BOARD) {
				do {
					fread(&time, 4, 1, f);
				} while(time >= 0);
				break;
			}
			
			tmp.m_times[i++] = time;
			fread(&time, 4, 1, f);
		}

		for(; i<BoardTimes::TIMES_PER_BOARD; ++i)
			tmp.m_times[i] = -1;
	
		m_times[buf] = tmp;
	}
	fclose(f);
}

void BestTimes::save(const char* filename)
{
	FILE* f = fopen(filename, "w");
	if (!f) {
		fprintf(stderr, "Warning: failed writing scores to file %s\n", filename);
		return;
	}
	const int32_t listEnd = -1;
	for(TimeMap::iterator i=m_times.begin(); i!=m_times.end(); ++i) {
		if (i->second.m_times[0] < 0)
			continue;
		uint32_t size = i->first.size();
		fwrite(&size, 4, 1, f);
		fwrite(i->first.c_str(), 1, i->first.size(), f);
		bool end = 0;
		for(int j=0; j<BoardTimes::TIMES_PER_BOARD; ++j) {
			int32_t value = i->second.m_times[j];
			if (value < 0) {
				fwrite(&listEnd, 4, 1, f);
				end = 1;
				break;
			}
			fwrite(&value, 4, 1, f);
		}
		if (!end)
			fwrite(&listEnd, 4, 1, f);
	}
	fclose(f);
}
