/* 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 BOARDPICKER_H
#define BOARDPICKER_H

#include "itempicker.h"
#include "gameloop.h"
#include "glscreen.h"
#include "sound.h"
#include "besttimes.h"
#include <fstream>

class BoardPicker: public ItemPicker<BoardPicker> {
public:
	template<class Iter1, class Iter2>
	BoardPicker(Iter1 boardBegin, Iter1 boardEnd, Iter2 packBegin, Iter2 packEnd, std::string prefix="levs/"):
		ItemPicker<BoardPicker>(boardBegin, boardEnd), m_prefix(prefix)
	{
		m_singleBoards = items.size();
		items.insert(items.end(), packBegin, packEnd);
	}
	template<class Iter>
	BoardPicker(Iter begin, Iter end, std::string prefix):
		ItemPicker<BoardPicker>(begin, end), m_prefix(prefix)
	{
		m_singleBoards = items.size();
	}

	void setString(int num, std::string& str) {
		if (num < m_singleBoards)
			str.erase(str.end()-3, str.end());
		else
			str.push_back('/');
	}
	std::string getTitle() {
		return std::string("choose board:");
	}
	bool pick(int num) {
		if (items.empty())
			return 0;
		if (num < m_singleBoards) {
			GameLoop::init();
			GameLoop game((m_prefix+items[num]).c_str());
			game.start();
			GameLoop::deInit();
		} else {
			std::string prefix = m_prefix+items[num]+'/';
			std::ifstream in((prefix+"info.txt").c_str());
			if (!in.is_open()) {
				fprintf(stderr, "Warning: couldn't open info file for level pack %s\n", items[num].c_str());
				return 1;
			}
			std::vector<std::string> tmp;
			char buf[1024];
			while(in) {
				if (!in.getline(buf, sizeof(buf)))
					break;
				if (!buf[0] || buf[0]=='#')
					continue;

				std::string str(buf);
				// check whether the board is locked
				if (BestTimes::getInstance().getTimes(prefix+str).getTimes()[0] < 0)
					break;

				tmp.push_back(str);
			}
			in.close();
			BoardPicker picker(tmp.begin(), tmp.end(), prefix);
			picker.exec();
		}
		return 1;
	}

private:
	std::string m_prefix;
	int m_singleBoards;
};

#endif
