#include <windows.h>
#include <mmsystem.h>
#include <cstdlib>
#include <cstdio>
#include <conio.h>
#include <cmath>
#include <iostream>
#include <fcntl.h>
#include <string.h>

#include "bass.h"
#include "timer.h"
#include "demo.h"
#include "api3ds.h"
#include "syncname.h"
#include "efekt.h"

/*
 * ak je premenna prepisovatelna zvonka, mala by byt deklarovana ako volatile.
 * tym je prekladac upozorneny, ze nema jej ulozenie/pracu s nou optimalizovat.
 * spominam si, ze toto bol znamy zdroj bugov pri starsich verziach midasu.
 */
volatile BOOL clear_zbuffer=TRUE;  // aby mohol efekt vypnut mazanie obrazovky
volatile BOOL clear_cbuffer=TRUE;  // nastavi si extern...
volatile BOOL usefog;

Texture3DS *loading;
bool showlogo=true;

Textures3DS *EFEKT::texture_library=0;

/*
 * config
 */
int       resx, resy, bpp;
BOOL      fullscreen;

/*
 * path to music stream
 */
#define module_name_na_fest "data\\mp3\\expiration.mp3"
char module_name[40];
int na_fest=0;

char*     className = "Peon demo";
char*     windowName= "Expiration";

HDC             hDC=NULL;               // Private GDI Device Context
HGLRC           hRC=NULL;               // Permanent Rendering Context
HWND            hWnd=NULL;              // Holds Our Window Handle
HINSTANCE       hInstance;              // Holds The Instance Of The Application

void display(void)
{
   glFlush();
   glFinish();
   SwapBuffers(hDC);
   if (clear_zbuffer&&clear_cbuffer)
     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   else {
     if (clear_zbuffer) glClear(GL_DEPTH_BUFFER_BIT);
     if (clear_cbuffer) glClear(GL_COLOR_BUFFER_BIT);
     }
}

int InitGL(GLvoid)
{
  InitOpenGLExtensions();
  glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
  glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  return TRUE;
}

#include "init_win.h"
#include "init_bas.h"

void drawlogo()
{
  glClearColor(0.0,0.0,0.0,1.0);

  loading->GL();
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glEnable(GL_TEXTURE_2D);
  glDisable(GL_LIGHTING);
  glDisable(GL_CULL_FACE);
  glDisable(GL_BLEND);
  glDisable(GL_DEPTH_TEST);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glBegin(GL_QUADS);
    glColor3f(1.0,1.0,1.0);
    glTexCoord2f( 1.0, 1.0);
    glVertex2f  (-0.5,-0.8);
    glTexCoord2f( 1.0, 0.0);
    glVertex2f  (-0.5,-1.0); 
    glTexCoord2f( 0.0, 0.0);
    glVertex2f  (-0.9,-1.0);
    glTexCoord2f( 0.0, 1.0);
    glVertex2f  (-0.9,-0.8);
  glEnd();

}

int APIENTRY
WinMain(
    HINSTANCE hCurrentInst,
    HINSTANCE hPreviousInst,
    LPSTR lpszCmdLine,
    int nCmdShow)
{

  //create texture library
  EFEKT::texture_library=new Textures3DS;
  Loader3DS::buffer=new char[1024*1024];

  // random generator init
  __int64  t;
  QueryPerformanceCounter((LARGE_INTEGER*)&t);
  t=-627438984;//3667528312
  srand((int)t);


  if(!DialogBox(hCurrentInst,MAKEINTRESOURCE(1000),0,&dialogproc)) return 0;

  float demo_start;
  DWORD hudba_start;

  FILE *stream=fopen("demo.cfg","r");
  if (stream) 
    {
    fscanf(stream,"hudba start   %i\n",&hudba_start);
    fscanf(stream,"demo  start   %f\n",&demo_start);
    fclose(stream);
    }
   else
    {
    hudba_start=0;
    demo_start=0.0;
    }

  stream=fopen("music.cfg","r");
  if (stream) 
    {
    fscanf(stream,"%s\n",module_name);
    fclose(stream);
    }
  else na_fest=1;

  if (!CreateGLWindow(windowName,resx,resy,bpp,fullscreen))
  {
    cout<<"createwindow failed"<<endl;
    return 0;
  }

  Textures3DS *texlib=EFEKT::texture_library;
  loading=texlib->GetOrCreate("LOADING.JPG");
  drawlogo();
  glFlush();
  glFinish();
  SwapBuffers(hDC);


  BOOL progress=demo_init();
  BOOL nomusic=0;  // nastavi sa na 1 ak nedoslo k spusteniu hudby


  if (!progress) {
    MessageBox(NULL,"DemoInit failed!","ERROR",MB_OK|MB_ICONEXCLAMATION);
    nomusic=1;
    }
   else
    if (!za_malo_penazi_vela_muziky()) {
      MessageBox(NULL,"MusicInit failed!","ERROR",MB_OK|MB_ICONEXCLAMATION);
      nomusic=1;
    }

  MSG msg;
  PTIMER timer;
  cout << endl << endl << endl << "DEMO:" << endl << endl;
  BASS_ChannelSetPosition((unsigned int)str,hudba_start);
  timer.reset(demo_start);
  bool space_pressed=false;
  while (progress) {
     while (progress&&(PeekMessage(&msg, hWnd, 0, 0, PM_NOREMOVE) == FALSE))
       {
       if (key[VK_SPACE]&&!space_pressed)
         {
         cout << "hudba start   "<< BASS_ChannelGetPosition((unsigned int)str) << endl;
         cout << "demo  start   " << timer.time() << endl;
         space_pressed=true;
         }
       if (!key[VK_SPACE]) space_pressed=false;

       progress=demo_go(timer.time());
       if (key[VK_ESCAPE]) progress=0;
       if (progress)
         {
         if (showlogo) drawlogo();
         display();
         }
      }
     if (!progress) SendMessage(hWnd,WM_CLOSE,0,0);
     if (GetMessage(&msg, hWnd, 0, 0) != TRUE) break;
     TranslateMessage(&msg);
     DispatchMessage(&msg);
     }

  KillGLWindow();
  if (!nomusic)
    {
    for (int a=100;a>=0;a-=1)
      {
      BASS_SetVolume(a);
      Sleep(5);
      }
    BASS_Free();
    }
  cout << "Random seed: " << (int)t << endl;
//  delete EFEKT::texture_library;
  return (msg.wParam);
}
