#include "TZ_Vendor_debug_tl.h"
#include "tl_tui_bc_error_msg.h"

#include "TuiPng.h"
#include "TuiRotation.h"

uint32_t validatePng(
	uint8_t * png_buf,	// buffer to png image
	uint32_t buf_len,	// png buffer length
	uint32_t * width,	// png image width
	uint32_t * height // png image height
)				
{
	uint8_t png_header[] = { 137, 80, 78, 71, 13, 10, 26, 10 };
	uint8_t ihdr_name[] = "IHDR";
	uint32_t i;

	*width = 0;
	*height = 0;

	if (buf_len < 8 + 4 + 4 + 4 + 4) {
		TTY_LOG("%s Buffer length (%d) is too small for PNG!", LOG_TAG,buf_len);
		return TIMA_ERROR_TUI_IMG_BAD_FORMAT;
	}

	if (memcmp(png_buf, png_header, 8)) {
		TTY_LOG("%s: Invalid PNG header!", LOG_TAG);
		return TIMA_ERROR_TUI_IMG_BAD_FORMAT;
	}

	if (memcmp(png_buf + 8 + 4, ihdr_name, 4)) {
		TTY_LOG("%s Not an IHDR chunk, invalid PNG file!", LOG_TAG);
		return TIMA_ERROR_TUI_IMG_BAD_FORMAT;
	}

	i = 8 + 4 + 4;

	DBG_LOG("TIMA TUI: PNG: %x %x %x %x   %x %x %x %x", png_buf[i], png_buf[i+1], png_buf[i+2], png_buf[i+3], png_buf[i+4], png_buf[i+5], png_buf[i+6], png_buf[i+7]);

	*width = png_buf[i++];
	*width = (*width << 8) + png_buf[i++];
	*width = (*width << 8) + png_buf[i++];
	*width = (*width << 8) + png_buf[i++];

	*height = png_buf[i++];
	*height = (*height << 8) + png_buf[i++];
	*height = (*height << 8) + png_buf[i++];
	*height = (*height << 8) + png_buf[i++];

	DBG_LOG("%s: PNG width = %d, height = %d", LOG_TAG, *width, *height);

	return TIMA_SUCCESS;
}

void getPngWidthAndHeight(uint8_t* image, uint32_t* width, uint32_t* height) {
	uint32_t itor = 16; // 8 + 4 + 4;
	uint32_t wTemp, hTemp;

	wTemp = image[itor++];
	wTemp = (wTemp << 8) + image[itor++];
	wTemp = (wTemp << 8) + image[itor++];
	wTemp = (wTemp << 8) + image[itor++];

	hTemp = image[itor++];
	hTemp = (hTemp << 8) + image[itor++];
	hTemp = (hTemp << 8) + image[itor++];
	hTemp = (hTemp << 8) + image[itor++];

	*width = wTemp;
	*height = hTemp;
}
