/*
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/renderer/surface.hpp"

#include <png.h>
#include <cstring>

#include "common/logger.hpp"

using namespace polygun::renderer;

Surface::Surface(unsigned width, unsigned height, const glm::vec4ub& color) :
	m_width(width),
	m_height(height),
	m_pixels(new uint8_t[width*height*4])
{
	fill(color);
}

Surface::Surface(unsigned width, unsigned height, const uint8_t* pixels) :
	m_width(width),
	m_height(height),
	m_pixels(new uint8_t[width*height*4])
{
	memcpy(m_pixels, pixels, width*height*4);
}

Surface::Surface() :
	m_width(0),
	m_height(0),
	m_pixels(nullptr)
{}

Surface::~Surface() {
	if(m_pixels)
		delete[] m_pixels;
}

void Surface::fill(const glm::vec4ub& color) {
	for(unsigned y = 0; y<m_height; y++) {
		for(unsigned x = 0; x<m_width; x++) {
			m_pixels[(y*m_width+x)*4] = color.r;
			m_pixels[(y*m_width+x)*4+1] = color.g;
			m_pixels[(y*m_width+x)*4+2] = color.b;
			m_pixels[(y*m_width+x)*4+3] = color.a;
		}
	}
}

void Surface::blit_surface(int x, int y, const Surface& other) {
	if(x+static_cast<int>(other.m_width)<=0 || y+static_cast<int>(other.m_height)<=0 || x>=static_cast<int>(m_width) || y>=static_cast<int>(m_height))
		return;
	unsigned x_skip = 0;
	unsigned y_skip = 0;
	if(x<0) {
		x_skip = std::abs(x);
		x = 0;
	}
	if(y<0) {
		y_skip = std::abs(y);
		y = 0;
	}
	for(unsigned py = y_skip; static_cast<int>(py)+y<static_cast<int>(m_height) && py<other.m_height; py++) {
		const int actual_y = static_cast<int>(py)+y;
		for(unsigned px = x_skip; static_cast<int>(px)+x<static_cast<int>(m_width) && px<other.m_width; px++) {
			const int actual_x = static_cast<int>(px)+x;
			const int offset = (py*other.m_width+px)*4;
			glm::vec4ub color;
			color.r = other.m_pixels[offset];
			color.g = other.m_pixels[offset+1];
			color.b = other.m_pixels[offset+2];
			color.a = other.m_pixels[offset+3];
			put_pixel(actual_x, actual_y, color);
		}
	}
}

void Surface::blit_surface(int x, int y, const Surface& other, unsigned dw, unsigned dh) {
	if(x+static_cast<int>(dw)<=0 || y+static_cast<int>(dh)<=0 || x>=static_cast<int>(m_width) || y>=static_cast<int>(m_height))
		return;
	unsigned x_skip = 0;
	unsigned y_skip = 0;
	if(x<0) {
		x_skip = std::abs(x);
		x = 0;
	}
	if(y<0) {
		y_skip = std::abs(y);
		y = 0;
	}
	const float x_scale_factor = static_cast<float>(other.m_width)/static_cast<float>(dw);
	const float y_scale_factor = static_cast<float>(other.m_height)/static_cast<float>(dh);
	for(float py = y_skip; std::floor(py)+y<m_height && std::floor(py)<other.m_height; py+=y_scale_factor) {
		const int actual_y = std::floor(py)+y;
		for(float px = x_skip; std::floor(px)+x<m_width && std::floor(px)<other.m_width; px+=x_scale_factor) {
			const int actual_x = std::floor(px)+x;
			const int offset = (py*other.m_width+px)*4;
			glm::vec4ub color;
			color.r = other.m_pixels[offset];
			color.g = other.m_pixels[offset+1];
			color.b = other.m_pixels[offset+2];
			color.a = other.m_pixels[offset+3];
			put_pixel(actual_x, actual_y, color);
		}
	}
}

bool Surface::load_from_file(const std::string& path) {
	FILE* file = fopen(path.c_str(), "rb");
	if(!file) {
		LOG_ERROR("Failed to open file '%s': ", path.c_str(), strerror(errno));
		return false;
	}

	unsigned char signature[8];
	fread(signature, 8, 1, file);
	if(png_check_sig(signature, 8)) {
		if(!load_png(file)) {
			LOG_ERROR("Failed to read PNG file '%s'", path.c_str());
			fclose(file);
			return false;
		}
		fclose(file);
		return true;
	}
	fclose(file);
	return false;
}

bool Surface::load_png(FILE* file) {
	png_structp png_struct = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
	if(!png_struct) {
		LOG_VERBOSE("Failed to create PNG read struct");
		return false;
	}

	png_infop png_info = png_create_info_struct(png_struct);
	if(!png_info) {
		png_destroy_read_struct(&png_struct, nullptr, nullptr);
		LOG_VERBOSE("Failed to create PNG info struct");
		return false;
	}

	png_init_io(png_struct, file);
	png_set_sig_bytes(png_struct, 8);
	png_read_info(png_struct, png_info);

	int bit_depth, color_type;
	png_get_IHDR(png_struct, png_info, &m_width, &m_height, &bit_depth, &color_type, nullptr, nullptr, nullptr);

	if(png_get_valid(png_struct, png_info, PNG_INFO_bKGD)) {
		unsigned char background_r, background_g, background_b;
		png_color_16p background;
		png_get_bKGD(png_struct, png_info, &background);
		if(bit_depth==16) {
			background_r = background->red>>8;
			background_g = background->green>>8;
			background_b = background->blue>>8;
		}
		else if(color_type==PNG_COLOR_TYPE_GRAY && bit_depth<8) {
			switch(bit_depth) {
			case 1:
				background_r = background_g = background_b = background->gray?255:0;
				break;
			case 2:
				background_r = background_g = background_b = 255/3*background->gray;
				break;
			default:
				background_r = background_g = background_b = (255/15)*background->gray;
				break;
			}
		}
		else {
			background_r = background->red;
			background_g = background->green;
			background_b = background->blue;
		}
		// TODO: Use background color
		(void)background_r;
		(void)background_g;
		(void)background_b;
	}

	if(color_type==PNG_COLOR_TYPE_PALETTE)
		png_set_expand(png_struct);
	if(color_type==PNG_COLOR_TYPE_GRAY && bit_depth<8)
		png_set_expand(png_struct);
	if(png_get_valid(png_struct, png_info, PNG_INFO_tRNS))
		png_set_expand(png_struct);

	if(bit_depth==16)
		png_set_strip_16(png_struct);
	if(color_type==PNG_COLOR_TYPE_GRAY || color_type==PNG_COLOR_TYPE_GRAY_ALPHA)
		png_set_gray_to_rgb(png_struct);

	// Note: this code assumes 2.2 gamma. This will work for most if not all modern monitors.
	// However to have maximal compatibility this shouldn't be hardcoded
	double gamma;
	if(png_get_gAMA(png_struct, png_info, &gamma))
		png_set_gamma(png_struct, 2.2, gamma);

	png_read_update_info(png_struct, png_info);
	unsigned row_bytes = png_get_rowbytes(png_struct, png_info);
	unsigned channels = png_get_channels(png_struct, png_info);
	uint8_t* image = new uint8_t[row_bytes*m_height];
	uint8_t** rows = new uint8_t*[m_height];
	for(unsigned i = 0; i<m_height; i++) {
		rows[i] = &image[row_bytes*i];
	}

	png_read_image(png_struct, rows);
	png_read_end(png_struct, nullptr);
	png_destroy_read_struct(&png_struct, &png_info, nullptr);

	switch(channels) {
	case 4:
		if(m_pixels)
			delete[] m_pixels;
		m_pixels = image;
		break;
	case 3:
		if(m_pixels)
			delete[] m_pixels;
		m_pixels = new uint8_t[m_width*m_height*4];
		for(unsigned y = 0; y<m_height; y++) {
			for(unsigned x = 0; x<m_width; x++) {
				const unsigned offset = (y*m_width+x)*4;
				const unsigned image_offset = (y*m_width+x)*3;
				m_pixels[offset] = image[image_offset];
				m_pixels[offset+1] = image[image_offset+1];
				m_pixels[offset+2] = image[image_offset+2];
				m_pixels[offset+3] = 255;
			}
		}
		delete[] image;
		break;
	default:
		LOG_VERBOSE("Invalid PNG image");
		delete[] image;
		delete[] rows;
		return false;
	}

	delete[] rows;
	return true;
}
