/*
    PNG functions
    Copyright (C) 2002-2020 Ladislav Vaiz <ok1zia@nagano.cz>
    and authors of tuxpaint http://www.newbreedsoftware.com/tuxpaint/
    and authors of libsdl-image

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#include <zpng.h>

#ifdef Z_HAVE_SDL
#include <SDL.h>
#endif

#include <zbinbuf.h>
#include <zdebug.h>
#include <zfile.h>
#include <zpath.h>
#include <zsdl.h>

#include <stdio.h>
#include <glib.h>
#ifdef Z_HAVE_LIBPNG
#include <png.h>
#endif

#ifdef Z_MSC
#pragma warning(disable : 4996)
#define _CRT_SECURE_NO_WARNINGS
#endif

/*int zpng_do_save(struct SDL_Surface * surf, char * fname, struct zbinbuf **buf);


int zpng_save(struct SDL_Surface * surf, char * fname){
	return zpng_do_save(surf, fname, NULL);
}

int zpng_save_mem(struct SDL_Surface * surf, struct zbinbuf **bbuf){
	return zpng_do_save(surf, NULL, bbuf);
}										  */

#if defined(Z_HAVE_SDL) && defined(Z_HAVE_LIBPNG)
static void zpng_write_data_fn(png_structp png_ptr, png_bytep data, png_size_t len){
	struct zbinbuf *bbuf = (struct zbinbuf *)png_get_io_ptr(png_ptr);
	zbinbuf_append_bin(bbuf, data, len);
}

static void zpng_flush_data_fn(png_structp png_ptr){
	//struct zbinbuf *bbuf = (struct zbinbuf *)png_get_io_ptr(png_ptr);
}
#endif

int zpng_save(struct SDL_Surface *surf, char *fname, struct zbinbuf *zbb)
{
#if defined(Z_HAVE_SDL) && defined(Z_HAVE_LIBPNG)
    png_structp png_ptr;
    png_infop info_ptr;
    png_text text_ptr[4];
    unsigned char ** png_rows;
    Uint8 r, g, b;
    int x, y, count;
    FILE *fi = NULL;

	dbg("zpng_save(%s)\n", fname);
	if (fname){
		z_wokna(fname);
		fi=fopen(fname,"wb");
		if (!fi){
			return -1;
		}
	}

    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (png_ptr == NULL)
    {
		if (fname) fclose(fi);
		png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
		return -2;
    }

	info_ptr = png_create_info_struct(png_ptr);
    if (info_ptr == NULL)
	{
        if (fname) fclose(fi);
	    png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
        return -3;
	}
	
	if (setjmp(png_jmpbuf(png_ptr)))
	{
	    if (fname) fclose(fi);
	    png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
	    return -4;
	}
    
	if (fname) png_init_io(png_ptr, fi);
	if (zbb) {
        png_set_write_fn(png_ptr, zbb, zpng_write_data_fn, zpng_flush_data_fn);
    }
	

	png_set_IHDR(png_ptr, info_ptr, surf->w, surf->h, 8,
    	PNG_COLOR_TYPE_RGB, 1, PNG_COMPRESSION_TYPE_DEFAULT, 
	PNG_FILTER_TYPE_DEFAULT);

    /* Set headers */

    count = 0;

    text_ptr[count].key = "Software";
    text_ptr[count].text = Z_PACKAGE " " Z_VERSION;
    text_ptr[count].compression = PNG_TEXT_COMPRESSION_NONE;
    count++;

    png_set_text(png_ptr, info_ptr, text_ptr, count);
    png_write_info(png_ptr, info_ptr);

    /* Save the picture: */

    png_rows = (unsigned char **)malloc(sizeof(char *) * surf->h);

    for (y = 0; y < surf->h; y++)
    {
        png_rows[y] = (unsigned char *)malloc(sizeof(char) * 3 * surf->w);

        for (x = 0; x < surf->w; x++)
        {
            SDL_GetRGB(z_getpixel(surf, x, y), surf->format, &r, &g, &b);

            png_rows[y][x * 3 + 0] = r;
            png_rows[y][x * 3 + 1] = g;
            png_rows[y][x * 3 + 2] = b;
        }
    }

    png_write_image(png_ptr, png_rows);

    for (y = 0; y < surf->h; y++) free(png_rows[y]);
    free(png_rows);

    png_write_end(png_ptr, NULL);
    png_destroy_write_struct(&png_ptr, &info_ptr);
    if (fname) fclose(fi);
	return 0;
#else
	return -1;
#endif
}


#define PNG_BYTES_TO_CHECK 4

#if defined(Z_HAVE_SDL) && defined(Z_HAVE_LIBPNG)
/* Load a PNG type image from an SDL datasource */
static void png_read_data(png_structp ctx, png_bytep area, png_size_t size)
{
	SDL_RWops *src;

	src = (SDL_RWops *)png_get_io_ptr(ctx);
	SDL_RWread(src, area, size, 1);
}

void zpng_error_fce(png_structp png, png_const_charp ch){
}

static SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src)
{
	SDL_Surface *volatile surface;
	png_structp png_ptr;
	png_infop info_ptr;
	png_uint_32 width, height;
	int bit_depth, color_type, interlace_type;
	Uint32 Rmask;
	Uint32 Gmask;
	Uint32 Bmask;
	Uint32 Amask;
	SDL_Palette *palette;
	png_colorp png_palette;
	int png_num_palette;
	png_bytep *volatile row_pointers;
	int row, i;
#ifdef SDL_SRCCOLORKEY
	volatile int ckey = -1;
#endif
	png_color_16 *transv;

	if ( !src ) {
		/* The error message has been set in SDL_RWFromFile */
		return NULL;
	}

	/* Initialize the data we will clean up when we're done */
	png_ptr = NULL; info_ptr = NULL; row_pointers = NULL; surface = NULL;

	/* Create the PNG loading context structure */
	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
		NULL, zpng_error_fce, NULL);
	if (png_ptr == NULL){
		error("Couldn't allocate memory for PNG file or incompatible PNG dll (%s)\n", PNG_LIBPNG_VER_STRING);
		goto done;
	}

	 /* Allocate/initialize the memory for image information.  REQUIRED. */
	info_ptr = png_create_info_struct(png_ptr);
	if (info_ptr == NULL) {
		error("Couldn't create image information for PNG file\n");
		goto done;
	}

	/* Set error handling if you are using setjmp/longjmp method (this is
	 * the normal method of doing things with libpng).  REQUIRED unless you
	 * set up your own error handlers in png_create_read_struct() earlier.
	 */
	if ( setjmp(png_jmpbuf(png_ptr)) ) {
		error("Error reading the PNG file.\n");
		goto done;
	}

	/* Set up the input control */
	png_set_read_fn(png_ptr, src, png_read_data);

	/* Read PNG header info */
	png_read_info(png_ptr, info_ptr);
	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
			&color_type, &interlace_type, NULL, NULL);

	/* tell libpng to strip 16 bit/color files down to 8 bits/color */
	png_set_strip_16(png_ptr) ;

	/* Extract multiple pixels with bit depths of 1, 2, and 4 from a single
	 * byte into separate bytes (useful for paletted and grayscale images).
	 */
	png_set_packing(png_ptr);

	/* scale greyscale values to the range 0..255 */
	if(color_type == PNG_COLOR_TYPE_GRAY)
		png_set_expand(png_ptr);

	/* For images with a single "transparent colour", set colour key;
	   if more than one index has transparency, or if partially transparent
	   entries exist, use full alpha channel */
	if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
	        int num_trans;
		Uint8 *trans;
		png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans,
			     &transv);
		if(color_type == PNG_COLOR_TYPE_PALETTE) {
		    /* Check if all tRNS entries are opaque except one */
		    int i, t = -1;
		    for(i = 0; i < num_trans; i++)
			if(trans[i] == 0) {
			    if(t >= 0)
				break;
			    t = i;
			} else if(trans[i] != 255)
			    break;
		    if(i == num_trans) {
			/* exactly one transparent index */
#ifdef SDL_SRCCOLORKEY
				ckey = t;
#endif
		    } else {
			/* more than one transparent index, or translucency */
			png_set_expand(png_ptr);
		    }
		}
		else{
#ifdef SDL_SRCCOLORKEY
			ckey = 0; /* actual value will be set later */
#endif
		}
	}

	if ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA )
		png_set_gray_to_rgb(png_ptr);

	png_read_update_info(png_ptr, info_ptr);

	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
			&color_type, &interlace_type, NULL, NULL);

	/* Allocate the SDL surface to hold the image */
	Rmask = Gmask = Bmask = Amask = 0 ; 
	if ( color_type != PNG_COLOR_TYPE_PALETTE ) {
		if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) {
			Rmask = 0x000000FF;
			Gmask = 0x0000FF00;
			Bmask = 0x00FF0000;
			Amask = (png_get_channels(png_ptr, info_ptr) == 4) ? 0xFF000000 : 0;
			//Amask = (info_ptr->channels == 4) ? 0xFF000000 : 0;
		} else {
		    //int s = (info_ptr->channels == 4) ? 0 : 8;
			int s = (png_get_channels(png_ptr, info_ptr) == 4) ? 0 : 8;
			Rmask = 0xFF000000 >> s;
			Gmask = 0x00FF0000 >> s;
			Bmask = 0x0000FF00 >> s;
			Amask = 0x000000FF >> s;
		}
	}
	surface = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height,
			//bit_depth*info_ptr->channels, Rmask,Gmask,Bmask,Amask);
			bit_depth*png_get_channels(png_ptr, info_ptr), Rmask,Gmask,Bmask,Amask);
	if ( surface == NULL ) {
		error("Out of memory\n");
		goto done;
	}

#ifdef SDL_SRCCOLORKEY // on my adroid SDL is not present
	if(ckey != -1) {
	        if(color_type != PNG_COLOR_TYPE_PALETTE)
			/* FIXME: Should these be truncated or shifted down? */
		        ckey = SDL_MapRGB(surface->format,
			                 (Uint8)transv->red,
			                 (Uint8)transv->green,
			                 (Uint8)transv->blue);
	        SDL_SetColorKey(surface, SDL_SRCCOLORKEY, ckey);
	}
#endif

	/* Create the array of pointers to image data */
	row_pointers = (png_bytep*) malloc(sizeof(png_bytep)*height);
	if (row_pointers == NULL) {
		error("Out of memory\n");
		SDL_FreeSurface(surface);
		surface = NULL;
		goto done;
	}
	for (row = 0; row < (int)height; row++) {
		row_pointers[row] = (png_bytep)
				(Uint8 *)surface->pixels + row*surface->pitch;
	}

	/* Read the entire image in one go */
	png_read_image(png_ptr, row_pointers);

	/* and we're done!  (png_read_end() can be omitted if no processing of
	 * post-IDAT text/time/etc. is desired)
	 * In some cases it can't read PNG's created by some popular programs (ACDSEE),
	 * we do not want to process comments, so we omit png_read_end

	png_read_end(png_ptr, info_ptr);
	*/

	/* Load the palette, if any */
	png_get_PLTE(png_ptr, info_ptr, &png_palette, &png_num_palette);
	palette = surface->format->palette;
	if ( palette ) {
	    if(color_type == PNG_COLOR_TYPE_GRAY) {
			palette->ncolors = 256;
			for(i = 0; i < 256; i++) {
				palette->colors[i].r = i;
				palette->colors[i].g = i;
				palette->colors[i].b = i;
			}
		}else if (png_num_palette > 0 ) {
				palette->ncolors = png_num_palette; 
				for( i=0; i<png_num_palette; ++i ) {
					palette->colors[i].b = png_palette[i].blue;
					palette->colors[i].g = png_palette[i].green;
					palette->colors[i].r = png_palette[i].red;
 				}
	    	}
	    
	}

done:	/* Clean up and return */
	png_destroy_read_struct(&png_ptr, info_ptr ? &info_ptr : (png_infopp)0,
								(png_infopp)0);
	if ( row_pointers ) {
		free(row_pointers);
	}
	return(surface); 
}

SDL_Surface *zpng_load(const char *filename){
    SDL_RWops *src;
    SDL_Surface *surface;
	char *f2;
    
	f2 = g_strdup(filename);
	z_wokna(f2);

    src=SDL_RWFromFile(f2, "rb");
    if (!src){
        g_free(f2);
        return NULL;
    }
    surface=IMG_LoadPNG_RW(src);
    SDL_RWclose(src);

	g_free(f2);
    return surface;
}

SDL_Surface *zpng_create(const void *data, int len){
    SDL_RWops *src;
    SDL_Surface *surface;
    
	if (len < 67) return NULL; // https://garethrees.org/2007/11/14/pngcrush/

    src=SDL_RWFromConstMem(data, len);
    surface=IMG_LoadPNG_RW(src);
    SDL_RWclose(src);
    return surface;
}
#endif

#ifdef Z_HAVE_LIBPNG
void zpng_get_version(GString *gs){
	g_string_append_printf(gs, "%d.%d.%d", PNG_LIBPNG_VER_MAJOR, PNG_LIBPNG_VER_MINOR, PNG_LIBPNG_VER_RELEASE);
}
#endif
