/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "game/engine/texture_atlas.hpp"

#include "game/renderer/master_renderer.hpp"
#include "game/renderer/texture.hpp"
#include "game/renderer/surface.hpp"
#include "game/engine/content_registry.hpp"
#include "game/engine/resource_manager.hpp"
#include "common/logger.hpp"

using namespace polygun::engine;

TextureAtlas::TextureAtlas(renderer::MasterRenderer* master_renderer, ContentRegistry& content_registry, ResourceManager& resource_manager) :
	utils::ThreadSafe(),
	m_content_registry(content_registry),
	m_resource_manager(resource_manager),
	m_atlas(master_renderer->create_texture()),
	m_atlas_surface(),
	m_construct_thread(),
	m_atlas_updated(false)
{}

TextureAtlas::~TextureAtlas() {
	delete m_atlas;
	if(m_construct_thread && m_construct_thread->joinable())
		m_construct_thread->join();
}

void TextureAtlas::construct() {
	acquire();
	m_construct_thread.reset(new std::thread(&TextureAtlas::construct_thread_func, this));
	release();
}

void TextureAtlas::update() {
	if(!m_atlas_updated)
		return;
	acquire();
	m_atlas->load_from_surface(*m_atlas_surface);
	release();
	m_atlas_updated = false;
}

void TextureAtlas::construct_thread_func() {
	unsigned max_texture_width = 0;
	unsigned max_texture_height = 0;
	const uint16_t surface_count = m_content_registry.get_registered_node_count()-1;
	renderer::Surface** surfaces = new renderer::Surface*[surface_count];
	for(uint16_t i = 1; i<m_content_registry.get_registered_node_count(); i++) {
		std::string texture_filename = m_content_registry.get_node_def(i).m_texture_filename;
		if(texture_filename.empty())
			continue;
		renderer::Surface& surf = m_resource_manager.get_surface(texture_filename);
		surfaces[i-1] = &surf;
		if(surf.get_width()>max_texture_width)
			max_texture_width = surf.get_width();
		if(surf.get_height()>max_texture_height)
			max_texture_height = surf.get_height();
	}
	std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now();
	while(m_resource_manager.is_pending()) {
		std::chrono::time_point<std::chrono::system_clock> tm = std::chrono::system_clock::now();
		std::chrono::duration<double> interval = tm-start;
		if(interval.count()>30) {
			LOG_WARNING("Waiting for node textures took too long, stopping");
			break;
		}
	}

	acquire();
	m_atlas_surface.reset(new renderer::Surface(max_texture_width*surface_count, max_texture_height));
	for(uint16_t i = 0; i<surface_count; i++)
		m_atlas_surface->blit_surface(i*max_texture_width, 0, *surfaces[i]);
	release();
	delete[] surfaces;

	m_atlas_updated = true;
}
