/*!
  \example inputDraw.cpp
  \brief TextInput の動作サンプル

  \author Satofumi KAMIMURA

  $Id: inputDraw.cpp 1814 2010-05-03 07:57:38Z satofumi $

  \todo setBackspaceEvent を設定する
*/

#include "Font.h"
#include "Screen.h"
#include "LayerManager.h"
#include "Layer.h"
#include "TextSurface.h"
#include "Label.h"
#include "TextInput.h"
#include "CallbackEvent.h"
#include "EventUtils.h"
#include "delay.h"
#include <iostream>

using namespace qrk;
using namespace std;


namespace
{
    void updateText(TextSurface*& text_surface, Label*& text_label,
                    Font& font, const char* text)
    {
        delete text_label;
        delete text_surface;
        text_surface = new TextSurface(font, text);
        text_label = new Label(*text_surface);
    }
}


int main(int argc, char *argv[])
{
    // フォントの読み出し
    if (argc <= 1) {
        cout << "usage:" << endl
             << '\t' << argv[0] << " <ttf font file>" << endl;
        exit(1);
    }
    const char* font_file = argv[1];

    Font font(font_file, 32);
    if (! font.isValid()) {
        exit(1);
    }

    // 画面の生成
    Screen screen;
    if (! screen.show(SDL_OPENGL)) {
        cout << "Screen::show(): " << screen.what() << endl;
        exit(1);
    }

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

    // 入力の取得用
    TextInput text_input;
    // !!! 削除イベントを登録する
    layer_manager.insertEvent(&text_input);


    // イベントの初期化
    CallbackEvent quit_event;
    setQuitEvent(&quit_event);
    layer_manager.insertEvent(&quit_event);

    CallbackEvent enter_event;
    setEnterEvent(&enter_event);
    layer_manager.insertEvent(&enter_event);


    // 文字列描画
    TextSurface* text_surface = NULL;
    Label* text_label = NULL;

    // 描画ループ
    bool quit = false;
    while (! quit) {
        layer_manager.updateEvent();
        quit |= quit_event.isActive();

        // 入力文字の取得と描画
        if (text_input.isChanged()) {
            // 文字列サーフェスの作り直し
            layer.remove(text_label);

            if (! text_input.empty()) {
                updateText(text_surface, text_label, font, text_input.text());
                layer.push_front(text_label);
            }
        }
        if (enter_event.isActive()) {
            // 取得文字列の表示
            cout << text_input.text() << endl;
            text_input.clear();
        }

        screen.clear();
        layer_manager.draw();
        layer_manager.swap();

        delay(10);
    }

    delete text_label;
    delete text_surface;

    return 0;
}
