
#include <iostream>
#include <Spectre/Display/Display.h>
#include <Spectre/Display/GLContext.h>
#include <Spectre/System/SystemEvent.h>
#include <Platform/PlatformDisplay.h>

#define CAPTION_DEFAULT "Spectre"
#define ICON_DEFAULT "./assets/app.ico"

Display::Display()
{
	m_caption = CAPTION_DEFAULT;
	m_fmode = WINDOWED;

	m_context = GLContext::create();
	m_impl = PlatformDisplay::make(this);
}

Display::~Display()
{
	delete m_context;
	delete m_impl;
}

bool Display::create(DisplayDescription description)
{
	destroy();

	if (!m_impl->create(description)) {
		return false;
	}

	if (!m_context->create(m_impl)) {
		return false;
	}

	init();

	m_description = description;

	return true;
}

void Display::init()
{
	m_impl->setCaption(m_caption);

	setIcon(ICON_DEFAULT);

	activate(true);

	enableVSync(false);
	showCursor(true);
}

void Display::destroy()
{
	m_context->destroy();

	m_impl->destroy();
}

void Display::setCaption(const std::string& caption)
{
	m_caption = caption;
	m_impl->setCaption(m_caption);
}

const std::string& Display::getCaption() const
{
	return m_caption;
}

void Display::setIcon(const std::string& filename)
{
	m_impl->setIcon(filename);
}

void Display::setSize(unsigned int width, unsigned int height)
{
	m_description.mode.width = width;
	m_description.mode.height = height;

	m_impl->setSize(width, height);
}

void Display::setVideoMode(Mode mode)
{
	DisplayDescription desc;

	if (m_fmode == mode) {
		return;
	}

	if (mode == FULLSCREEN || mode == WINDOWEDFULLSCREEN) {

		// True fullscreen
		if (mode == FULLSCREEN) {
			desc.mode = m_description.mode;
		} else {
			desc.mode = DisplayMode::getDesktopMode();
			m_cacheDesc = m_description;
		}

		desc.decoration = DisplayDecorate::None;
	} else {
		desc = m_cacheDesc;
	}

	create(desc);

	m_fmode = mode;
}

enum Display::Mode Display::getVideoMode() const
{
	return m_fmode;
}

void Display::showCursor(bool value)
{
	m_impl->showCursor(value);
}

bool Display::activate(bool value)
{
	if (value) {
		return m_context->activate();
	}
	return m_context->deactivate();
}

bool Display::enableVSync(bool value)
{
	return m_context->setSwapInterval(value ? 1 : 0);
}

void Display::swapBuffers()
{
	if (activate(true)) {
		m_context->swapBuffers();
	}
}

void Display::onReshape(int width, int height)
{
	// Resize context if the windows resizes.
	m_context->setSize(width, height);
}