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

#include "SDL.h"
#include <vector>
#include "common.h"

/**
 * Base class for all menus in the game.
 * Expects template parameter Derived to implement
 * the following member functions:
 * - bool processKey(SDLKey key);
 * - void draw();
 */
template<class Derived, class Item>
class MenuBase {
public:
	typedef Item item_t;
	typedef std::vector<item_t> ItemList;
	
	MenuBase() {}

	template<class Iter>
	MenuBase(Iter begin, Iter end):
		items(begin, end)
		{}
	
	void exec() {
		SDL_Event e;
		activeItem = 0;
		while(1) {
			static_cast<Derived*>(this)->draw();
			SDL_WaitEvent(&e);
			do {
				if (e.type == SDL_QUIT) {
					exit(0);
				} else if (e.type == SDL_KEYDOWN) {
					SDLKey key = e.key.keysym.sym;
					if (key == SDLK_DOWN) {
						if (++activeItem == items.size())
							activeItem = 0;
					} else if (key == SDLK_UP) {
						if (activeItem == 0)
							activeItem = items.size()-1;
						else --activeItem;
					} else if (key == SDLK_ESCAPE)
						return;
					else {
						if (!static_cast<Derived*>(this)->processKey(e.key.keysym.sym))
							return;
					}
				}
			} while (SDL_PollEvent(&e));
		}
	}
protected:
	ItemList items;
	uint activeItem;
};

#endif
