#include <allegro5/allegro.h>
#include <allegro5/a5_primitives.h>
#include <allegro5/a5_font.h>
#include <allegro5/a5_iio.h>
#include <allegro5/a5_ttf.h>
#include <allegro5/a5_opengl.h>
#include <allegro5/acodec.h>
#include <allegro5/kcm_audio.h>
#include <cstdlib>
#include <cstdio>
#include <vector>

#include "prep/a5dumb.h"
#include "misc/Config.h"
#include "misc/Theme.h"
#include "state/TitleState.h"
#include "state/EditorState.h"

void die(const char *argh)
{
	std::printf("FATAL: %s.\n", argh);
	std::exit(1);
}

int main(int argc, char **argv)
{
	bool fullscreen = false;
	if (argc != 1)
		if (!strcmp(argv[1], "-fs"))
			fullscreen = true;

	if (!al_init()) die("Unable to initialize Allegro 5.");
	if (!al_init_iio_addon()) die("Unable to initialize IIO addon.");
	al_init_font_addon();
	if (!al_init_ttf_addon()) die ("Unable to initialize ttf addon.");

	al_set_new_display_flags(ALLEGRO_OPENGL | (fullscreen ? ALLEGRO_FULLSCREEN : ALLEGRO_WINDOWED));
	al_set_new_display_option(ALLEGRO_VSYNC, ALLEGRO_SUGGEST, 2);
	ALLEGRO_DISPLAY *disp = al_create_display(800, 600);
	if (!disp) die("Unable to create an OpenGL display.");

	al_install_keyboard();
	al_install_mouse();
	al_show_mouse_cursor();

	if (al_install_audio(ALLEGRO_AUDIO_DRIVER_AUTODETECT))
	{
		al_reserve_samples(16);
		al_init_dumb_addon(DUMB_RQ_LINEAR);
		al_duh_set_volume(al_play_module("media/dreamland.xm", 0, true), 0.25f);
	}
	else
	{
		die("Unable to initialize audio.");
	}

	// init
	int numLevels = 1;
	FILE *f;
	while (f = fopen(SPrintF::format("levels/%d.lv", numLevels).c_str(), "r"))
	{
		numLevels++;
		fclose(f);
	}
	numLevels--;
	Config::get().initialize(numLevels);
	Theme::initialize();

	// play
	if (argc < 2 || strcmp(argv[1], "-editor"))
	{
		TitleState ts;
		ts.runAsMain();
		Config::get().save();
	}
	else
	{
		EditorState es;
		es.runAsMain();
	}

	al_destroy_display(disp);

	return 0;
}
END_OF_MAIN()
