#include <SDL/SDL.h>

#undef main

#include "project_run.h"
#include "project_script.h"
#include "project_controls.h"

SDL_Event event;

// ==================
// ==== Controls ====
// ==================

int previous_mouse_x = 0;
int previous_mouse_y = 0;
int LMB_pressed = false;
int RMB_pressed = false;

const int iso_add = 8;

vol_control *vc;

void SetVctrl(vol_control *v)
{
	vc = v;
}

void MouseActions(int x, int y)
{
    if (LMB_pressed)
    {
        vc->rot_vecs.x += -(y - previous_mouse_y) / 64.0f;
        vc->rot_vecs.y += -(x - previous_mouse_x) / 64.0f;
	}

    if (RMB_pressed)
    {
        vc->cam_zoom += (y - previous_mouse_y) / 32.0f;
        if (vc->cam_zoom < 0.0f) vc->cam_zoom = 0.0f;
        if (vc->cam_zoom > 4.0f) vc->cam_zoom = 4.0f;
    }
}

void ControlsHandling()
{
	while (SDL_PollEvent(&event))
	{
		switch (event.type)
		{
			case SDL_QUIT:
				quit=true;
			break;

			case SDL_KEYDOWN:
				if (event.key.keysym.sym==SDLK_ESCAPE)
				{
					quit=true;
				}

				if (event.key.keysym.sym==SDLK_SPACE)
				{
					NewPart((GetPart() + 1) % ENDPART);
				}

				if (event.key.keysym.sym==SDLK_v)
				{
					limit_speed = !limit_speed;
				}
			break;

			case SDL_MOUSEMOTION:
				MouseActions(event.motion.x, event.motion.y);
				previous_mouse_x = event.motion.x;
				previous_mouse_y = event.motion.y;
			break;

			case SDL_MOUSEBUTTONUP:
				if (event.button.button == SDL_BUTTON_LEFT)
					LMB_pressed = false;
				if (event.button.button == SDL_BUTTON_RIGHT)
					RMB_pressed = false;
			break;

			case SDL_MOUSEBUTTONDOWN:
				if (event.button.button == SDL_BUTTON_LEFT)
					LMB_pressed = true;
				if (event.button.button == SDL_BUTTON_RIGHT)
					RMB_pressed = true;

				if (event.button.button == SDL_BUTTON_WHEELUP)
				{
					vc->iso_surf += iso_add;
					if (vc->iso_surf > 255) vc->iso_surf = 255;
					printf("%d\n",vc->iso_surf);
				}
				if (event.button.button == SDL_BUTTON_WHEELDOWN)
				{
					vc->iso_surf -= iso_add;
					if (vc->iso_surf < 0) vc->iso_surf = 0;
					printf("%d\n",vc->iso_surf);
				}
			break;
		}
	}
}

void Controls()
{
	ControlsHandling();
}
