#include <Basis/Screen.hpp>
#include "Jam.hpp"

#include "mixer.hpp"
#include "live_plate.hpp"

#include <Graphics/Graphics.hpp>

#include <SDL.h>
#include <SDL_opengl.h>

#include <string>
#include <sstream>

#include <Basis/Error.hpp>


using std::istringstream;
using std::string;

int main(int argc, char **argv) {
	srand(time(0));

	//standard screen.
	Graphics::screen_x = 768;
	Graphics::screen_y = 1024;
	if (argc == 2) {
		Graphics::fullscreen = true;
	} else if (argc >= 3) {
		istringstream params(string(argv[1]) + " " + string(argv[2]));
		params >> Graphics::screen_x >> Graphics::screen_y;
	}
	if (argc == 4) {
		Graphics::fullscreen = true;
	}
	INFO("Trying to run at " << Graphics::screen_x << " x " << Graphics::screen_y << " (Fullscreen = " << Graphics::fullscreen << ")");

	//if (argc != 2) {
	//	ERROR("Please pass working directory on command line.");
	//	return 0;
	//}

	if (SDL_Init(SDL_INIT_TIMER) != 0) {
		ERROR("Could not initialize sdl: " << SDL_GetError());
		return 1;
	}

	if (!Graphics::init(Graphics::NEED_VSYNC)) {
		ERROR("Could not initialize graphics, not continuing.");
		exit(1);
	}

	if (!Mixer::init()) {
		ERROR("Could not initialize audio, not continuing.");
		exit(1);
	}

	//Some quick basic GL state:
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glScalef(1.0f / Graphics::aspectf(), 1.0f, 1.0f);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

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

	//we'll draw our own cursor, thank you.
	SDL_ShowCursor(SDL_DISABLE);


	LivePlate::init(); //start live plate rendering thread.
	ImageWatcher::init(); //scan for incoming photos

/*
	Sint16 wave[100];
	for (unsigned int i = 0; i < 100; ++i) {
		wave[i] = (int)((1 << 8) * sinf(i / float(100) * M_PI * 2.0f));
	}
	SDL_LockAudio();
	Mixer::samples.push_back(Mixer::Sample(wave, 100));
	SDL_UnlockAudio();

	Sint16 sh[1500];
	for (unsigned int i = 0; i < 1500; ++i) {
		sh[i] = (int)((1 << 10) * ((rand() / float(RAND_MAX) - 0.5f) * i / float(1500)));
	}

	while (1) {
		if (Mixer::underruns) {
			WARNING(Mixer::underruns << " under-runs.");
			Mixer::underruns = 0;
		}
		SDL_Delay(500);
		LivePlate::live_plate.pos[4] = (1 << 16);
		SDL_Delay(500);
		SDL_LockAudio();
		Mixer::samples.push_back(Mixer::Sample(sh, 1500, false));
		SDL_UnlockAudio();
	}
*/

	Jam jam;

	start_screen(&jam);

	ImageWatcher::deinit();
	LivePlate::deinit();
	Mixer::deinit();
	Graphics::deinit();

	SDL_Quit();

	return 0;
}
