#include "pw/system/window.hpp"

#include "GLFW/glfw3.h"
//#include "glad/glad.h"

#include "pw/visual/context.hpp"

#include <iostream>

namespace pw {

struct window_context : context {
	virtual bool make_current() override;
	virtual void resize() override;
//	virtual context::size size() override;
	virtual void flush() override;
};

bool window_context::make_current()
{
}

void window_context::resize()
{
}

void window_context::flush()
{
}

struct window::impl {

	GLFWwindow *_window = nullptr;

//	window_context _context;

	static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
	{
		window::impl* impl = static_cast<window::impl*>(glfwGetWindowUserPointer(window));
//		impl->on_resize(width,height);

//		std::cout << "framebuffer " << width << "x" << height << std::endl;
	//	glViewport(0, 0, width, height);
	}

	impl()
	{
		glfwInit();

		_window = glfwCreateWindow(640, 480, "pixwerxs", nullptr, nullptr);

		glfwSetWindowUserPointer(_window,this);
		glfwSetFramebufferSizeCallback(_window, window::impl::framebuffer_size_callback);


#if 0
	glfwMakeContextCurrent(_window);

	gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);

#endif
	}

	~impl()
	{
		glfwDestroyWindow(_window);
	}

	bool update()
	{
		if (!glfwWindowShouldClose(_window)) {

			glfwPollEvents();

			// do other stuff
#if 0
			glClearColor(1,0,0,1);
			glClear(GL_COLOR_BUFFER_BIT);
#endif

			glfwSwapBuffers(_window);

			return true;
		}

		return false;

	}

	void set_title(const std::string& title)
	{
		glfwSetWindowTitle(_window,title.c_str());
	}

	void set_size(int w,int h)
	{
		glfwSetWindowSize(_window,w,h);
	}


};


window::window()
	: _impl(std::make_unique<window::impl>())
{
}

window::~window()
{
}

bool window::update()
{
	return _impl->update();
}

void window::set_title(const std::string& title)
{
	_impl->set_title(title);
}

void window::set_size(int w,int h)
{
	_impl->set_size(w,h);
}

int window::get_width()
{
//	int w,h;
//	glfwGetWindowSize(_window,&w,&h);
//	return w;
}

int window::get_heigth()
{
//	int w,h;
//	glfwGetWindowSize(_window,&w,&h);
//	return h;
}


}
