/*!
  \file
  \brief Lua スクリプトの実行用 (クライアント)

  \author Satofumi KAMIMURA

  $Id: client.cpp 1140 2009-07-13 21:41:41Z satofumi $
*/

#include "port.h"
#include "Screen.h"
#include "LayerManager.h"
#include "SlaveLayer.h"
#include "CallbackEvent.h"
#include "EventUtils.h"
#include "PacketUtils.h"
#include "Packet.h"
#include "TcpipSocket.h"
#include "CycleTimer.h"
#include "delay.h"
#include <iostream>

using namespace qrk;
using namespace std;


namespace
{
  void runClient(Connection& con)
  {
    LayerManager layer_manager;
    SlaveLayer layer;
    layer_manager.push_front(&layer);

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

    Screen screen;
    CycleTimer cycle_timer;
    bool quit = false;
    while (! quit) {

      screen.clear();
      layer_manager.updateEvent();
      quit |= quit_event.isActive();

      // パケットの受信
      Packet packet;
      while (PacketControl::receive(packet, &con)) {
        string type = packetType(packet);
        static_cast<void>(type);

        if (! type.compare("SY")) {
          layer.setPacket(packet);
        }
      }

      layer_manager.draw();
      layer_manager.swap();

      delay(cycle_timer.waitMsec());
    }
  }
}


int main(int argc, char *argv[])
{
  Screen screen;
  if (! screen.show(SDL_OPENGL)) {
    cout << "Screen::show: " << screen.what() << endl;
    exit(1);
  }

  TcpipSocket con;
  if (! con.connect("localhost", Port)) {
    cout << "TcpipSocket::connect: " << con.what() << endl;
    exit(1);
  }

  runClient(con);
  return 0;
}
