#include <allegro5/allegro.h>
#include <allegro5/allegro_direct3d.h>
#include <iostream>

int main() {

	al_init();

	ALLEGRO_EVENT_QUEUE* eventQueue = al_create_event_queue();

	al_inhibit_screensaver(true);

	// Allegro bitmap setup
	al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ARGB_8888);
	al_add_new_bitmap_flag(ALLEGRO_VIDEO_BITMAP);
	al_add_new_bitmap_flag(ALLEGRO_NO_PRESERVE_TEXTURE);

	// Display options and flags
	al_set_new_display_option(ALLEGRO_VSYNC, 0, ALLEGRO_SUGGEST);

	int displayFlags = 0;
	displayFlags |= ALLEGRO_DIRECT3D;
	displayFlags |= ALLEGRO_WINDOWED;
	displayFlags |= ALLEGRO_RESIZABLE;

	al_set_new_display_flags(displayFlags);

	ALLEGRO_DISPLAY* display = al_create_display(400, 400);

	al_register_event_source(eventQueue, al_get_display_event_source(display));

	// Render timer
	ALLEGRO_TIMER* renderTimer = al_create_timer(1.0 / 10);
	al_register_event_source(eventQueue, al_get_timer_event_source(renderTimer));

	// Test bitmap
	ALLEGRO_BITMAP* testBitmap = al_create_bitmap(100, 100);
	al_set_target_bitmap(testBitmap);
	al_clear_to_color(al_map_rgb(0, 0, 255));

	al_start_timer(renderTimer);

	// Event loop
	ALLEGRO_EVENT event;

	while (true) {

		al_wait_for_event(eventQueue, &event);

		if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
			break;
		}
		else if (event.type == ALLEGRO_EVENT_DISPLAY_FOUND) {
			std::cout << "display found" << std::endl;
		}
		else if (event.type == ALLEGRO_EVENT_DISPLAY_LOST) {
			std::cout << "display lost" << std::endl;
		}
		else if (event.type == ALLEGRO_EVENT_DISPLAY_RESIZE) {
			std::cout << "display resize" << std::endl;
			al_acknowledge_resize(event.display.source);
		}
		// Render timer
		else if (event.type == ALLEGRO_EVENT_TIMER) {
			al_set_target_backbuffer(display);
			al_clear_to_color(al_map_rgb(0, 0, 0));
			al_draw_bitmap(testBitmap, 10, 10, 0);
			al_flip_display();
		}
	}

	// Cleanup stuff
	al_destroy_timer(renderTimer);
	al_destroy_bitmap(testBitmap);
	al_unregister_event_source(eventQueue, al_get_display_event_source(display));
	al_destroy_display(display);
	al_destroy_event_queue(eventQueue);

	return EXIT_SUCCESS;
}