/* 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.
 */

#ifndef BESTTIMES_H
#define BESTTIMES_H

#include <map>
#include <string>
#include <algorithm>
#include <cstdio>

class BestTimes;

class BoardTimes {
public:
	enum {TIMES_PER_BOARD=5};

	BoardTimes() {
		for(int i=0; i<TIMES_PER_BOARD; ++i) {
			m_times[i] = -1;
		}
	}

	int insert(int time) {
		// FIXME: use binary search
		for(int i=0; i<TIMES_PER_BOARD; ++i) {
			if (m_times[i] < 0) {
				m_times[i] = time;
				return i;
			} else if (m_times[i] > time) {
				for(int j=TIMES_PER_BOARD-1; j>i; --j)
					m_times[j] = m_times[j-1];
				m_times[i] = time;
				return i;
			}
		}
		return -1;
	}

	int amount() {
		return std::lower_bound(m_times, m_times+TIMES_PER_BOARD, -1, Cmp()) - m_times;
	}

	const int* getTimes() const {
		return m_times;
	}

	friend class BestTimes;
private:	
	int m_times[TIMES_PER_BOARD];

	class Cmp {
	public:
		bool operator()(int a, int b) {
			if (a < 0) {
				return 0;
			} else if (b < 0)
				return 1;
			return a<b;
		}
	};
};

class BestTimes {
public:
	static BestTimes& getInstance() {
		return m_instance;
	}
	
	void load(const char* file);
	void save(const char* file);
	
	BoardTimes& getTimes(const std::string& board) {
		return m_times[board];
	}

private:
	typedef std::map<std::string, BoardTimes> TimeMap;
	TimeMap m_times;

	static BestTimes m_instance;
};

#endif
