#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "level.h"
#include "objects.h"

static Level *level;
static int screenshot_mode = 0;          // position for screenshot

static void display_callback()
{
	level_draw(level);

	glutSwapBuffers();
}

static void timer_callback(int value)
{
	glutTimerFunc(50, timer_callback, 0);

	if (!screenshot_mode)
		level_run(level);
	
	display_callback();
}

static void restart_level()
{
	level_destroy(level);
	level = level_new();
}

static void keyboard_callback(unsigned char key, int x, int y)
{
	switch (tolower(key)) {
	case 't':
		restart_level();
		level->tourmode = !level->tourmode;
		break;
	case 'p':
		screenshot_mode = !screenshot_mode;
		if (screenshot_mode) {
			restart_level();
			
			level->chasecam.enabled = 0;
		}
		break;
	case ' ':
		if (level->gameover) {
			restart_level();
		}
		break;
	case 'c':
		level->chasecam.enabled = !level->chasecam.enabled;
		break;
	case 'f':
		level->draw_fireworks = !level->draw_fireworks;
		if (level->draw_fireworks)
			level->chasecam.enabled = 0;
		break;
	case 'h':
		printf("HELP:\n"
		       "\n"
		       "c:       switch camera view\n"
		       "f:       activate firework display\n"
		       "space:   restart game after gameover\n"
		       "p:       place in screenshot position\n"
		       "q:       quit\n"
		       "t:       activate tour mode\n");
		break;
	case 'q':
		exit(0);
	}
}

static void special_callback(int key, int x, int y)
{
	switch (key) {
	case GLUT_KEY_UP:
		player_set_movedir(level->player, 0);
		break;
	case GLUT_KEY_DOWN:
		player_set_movedir(level->player, 180);
		break;
	case GLUT_KEY_LEFT:
		player_set_movedir(level->player, 90);
		break;
	case GLUT_KEY_RIGHT:
		player_set_movedir(level->player, -90);
		break;
	default:
		// dont care
	}
}

int main(int argc, char *argv[])
{
	srand(clock());
	glutInit(&argc, argv);

	glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH);
	glutCreateWindow("pacman!");

	glClearColor(0, 0, 0, 1);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glFrustum(-0.4, 0.4, -0.3, 0.3, 0.4, 200);
	glMatrixMode(GL_MODELVIEW);
	
	level = level_new();

	glutTimerFunc(50, timer_callback, 0);
	glutDisplayFunc(display_callback);
	glutSpecialFunc(special_callback);
	glutKeyboardFunc(keyboard_callback);
	
	glutMainLoop();

	return 0;
}
