/*!
  \example menuSample.cpp
  \brief Menu の動作サンプル

  \author Satofumi KAMIMURA

  $Id: menuSample.cpp 897 2009-05-17 20:59:55Z satofumi $
*/

#include "Menu.h"
#include "Screen.h"
#include "LayerManager.h"
#include "Layer.h"
#include "Font.h"
#include "TextSurface.h"
#include "Button.h"
#include "CallbackEvent.h"
#include "EventUtils.h"
#include "delay.h"
#include <string>
#include <iostream>

using namespace qrk;
using namespace std;


int main(int argc, char *argv[])
{
  string font_file = "font.ttf";
  if (argc >= 2) {
    font_file = argv[1];
  }

  Screen screen;
  screen.show(SDL_OPENGL);

  LayerManager layer_manager;
  Layer layer;
  layer_manager.push_back(&layer);

  // フォントの初期化
  enum {
    FontSize = 40,
  };
  Font font(font_file.c_str(), FontSize, false);
  Font focused_font = font;
  focused_font.setBackgroundColor(Color(0.5f, 0.5f, 1.0f));
  Font clicked_font = focused_font;
  clicked_font.setForegroundColor(Color(0.0f, 0.0f, 0.0f));

  // メニューの作成
  Menu menu(Rect<long>(0, 0, 640, 480), Menu::Center);

  // ボタンの作成と登録
  vector<TextSurface*> text_surfaces;
  vector<Button*> buttons;
  const char* buttons_text[] = {
    " New Game ", " Load Game ", " Config ", " Exit ",
  };
  size_t n = sizeof(buttons_text) / sizeof(buttons_text[0]);
  for (size_t i = 0; i < n; ++i) {
    const char* text = buttons_text[i];
    TextSurface* surface = new TextSurface(font, text);
    TextSurface* focused_surface = new TextSurface(focused_font, text);
    TextSurface* clicked_surface = new TextSurface(clicked_font, text);
    Button* button = new Button(*surface, *focused_surface, *clicked_surface);


    menu.addButton(*button, i);

    text_surfaces.push_back(clicked_surface);
    text_surfaces.push_back(focused_surface);
    text_surfaces.push_back(surface);
    buttons.push_back(button);
  }

  layer.push_front(&menu);

  CallbackEvent quit_event;
  setQuitEvent(&quit_event);
  layer_manager.insertEvent(&quit_event);

  int clicked_count = 0;
  while (! quit_event.isActive()) {

    layer_manager.updateEvent();

    if (menu.isClicked()) {

      if (clicked_count == 0) {
        cout << "clicked: " << menu.clickedId() << endl;
      }
      ++clicked_count;
    }

    if (clicked_count > 100) {
      clicked_count = 0;
      menu.release();
    }

    screen.clear();
    layer_manager.draw();
    layer_manager.swap();
    delay(10);
  }

  for (vector<TextSurface*>::iterator it = text_surfaces.begin();
       it != text_surfaces.end(); ++it) {
    delete *it;
  }
  for (vector<Button*>::iterator it = buttons.begin();
       it != buttons.end(); ++it) {
    delete *it;
  }

  return 0;
}
