#include <GL/glut.h>
#include <string>
#include <sstream>

#include "glpng/glpng.h"

#include "CWinStream.h"
#include "CMove.h"
#include "CException.h"
#include "Pieces.h"
#include "CBoard.h"
#include "CTexture.h"
#include "CWindow.h"
#include "CActiveWin.h"
#include "CWindowSection.h"
#include "CSectionBoard.h"
#include "CMainWin.h"
#include "CStartUpWin.h"


CMainWin* p_MainWin;



void CMainWin::Display(void)
{
  glClear(GL_COLOR_BUFFER_BIT);

  extern std::string Text;
  wout.Begin();
  wout.SetColor(1,1,0,1);
  wout.SetPos(100, 100);
  wout << Text;
  wout.End();

  BoardWin->Display();

  glutSwapBuffers();
}

void CMainWin::Keyboard(unsigned char key, int x, int y)
{
  switch(key)
    {
    case ' ': exit(0); break;
    case 'W': *g_Window = p_StartUpWin; break;
    default: break;
    }
}

void CMainWin::Reshape(int w, int h)
{
  glViewport(0, 0, (GLint) w, (GLint) h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluOrtho2D(-1, 9, 9, -1);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  wout.SetToWindow();

  BoardWin->SetWidth(w >> 1);
  BoardWin->SetHeight(h >> 1);
}


void CMainWin::Mouse(int button, int state, int x, int y)
{
  BoardWin->Mouse(button,
                  state, x - BoardWin->GetPosX(),
                  y - BoardWin->GetPosY());
}


void CMainWin::Motion(int x, int y)
{
  BoardWin->Motion(x - BoardWin->GetPosX(), y - BoardWin->GetPosY());
}


void CMainWin::init(void)
{
  glClearColor(0,0.3,0,0);

  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable(GL_BLEND);

  Reshape(Width, Height);
}


CMainWin::CMainWin(const std::string& caption, int width, int height) 
  : CWindow(),
    ChessTexture("images/chess1.png"),
    BoardTexture("images/board1.png")
{
  Width = width;
  Height = height;
  Caption = caption;

  SetDisplayFunc((DisplayType) &CMainWin::Display);
  SetKeyboardFunc((KeyboardType) &CMainWin::Keyboard);
  SetReshapeFunc((ReshapeType) &CMainWin::Reshape);
  SetMotionFunc((MotionType) &CMainWin::Motion);
  SetMouseFunc((MouseType) &CMainWin::Mouse);


  BoardWin = new CSectionBoard(this, BoardTexture, ChessTexture, CBoard());
  if (!BoardWin)
    throw MEMORY_ERROR;
  BoardWin->LoadTexture();
}
