/*$
apdtool
Copyright (c) 2020 Azel

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.
$*/

/*****************************************
 * APD ver2 読み込み
 *****************************************/

#include <stdio.h>

#include "mlk.h"
#include "mlk_zlib.h"
#include "mlk_stdio.h"
#include "mlk_imagebuf.h"

#include "def.h"


//------------------

typedef struct
{
	FILE *fp;
	mZlib *zdec;
	mImageBuf2 *img;
	uint8_t *tilebuf;
	LayerData *layer;
	
	int w,h;
}APDv2Data;

//--------------

static const uint32_t g_tilesize_tbl[4] = {64*64*2*4, 64*64*2*2, 64*64*2, 64*64/8};

static const func_set_tileimage g_funcs_settile[4] = {
	set_tileimage_rgba16, set_tileimage_graya16, set_tileimage_a16, set_tileimage_a1
};

static const func_blendtile g_funcs_blendtile[4] = {
	blendtile_rgba16, blendtile_graya16, blendtile_a16, blendtile_a1
};

//------------------


/** タイルイメージスキップ */

static mlkerr _skip_tiles(FILE *fp,uint32_t tilenum)
{
	uint32_t pos,size;

	for(; tilenum; tilenum--)
	{
		if(mFILEreadFormatBE(fp, "ii", &pos, &size)
			|| fseek(fp, size, SEEK_CUR))
			return MLKERR_DAMAGED;
	}

	return MLKERR_OK;
}

/** レイヤイメージ読み込み (レイヤ抽出用) */

static mlkerr _read_layer_image(LayerData *pl,void *ptr)
{
	APDv2Data *p = (APDv2Data *)ptr;
	FILE *fp;
	uint8_t *tilebuf;
	uint32_t pos,size,tilesize,i;
	int tilew;
	func_set_tileimage func;
	mlkerr ret;

	fseeko(p->fp, pl->fpos, SEEK_SET);

	image_fill_zero(p->img);

	fp = p->fp;
	tilebuf = p->tilebuf;
	tilew = pl->tilew;
	tilesize = g_tilesize_tbl[pl->coltype];
	func = g_funcs_settile[pl->coltype];

	for(i = pl->imgparam; i; i--)
	{
		//タイル情報
		
		if(mFILEreadFormatBE(fp, "ii", &pos, &size)
			|| size > tilesize)
			return MLKERR_DAMAGED;

		//タイル読み込み

		if(size == tilesize)
		{
			if(fread(tilebuf, 1, tilesize, fp) != tilesize)
				return MLKERR_DAMAGED;
		}
		else
		{
			mZlibDecReset(p->zdec);

			ret = mZlibDecReadOnce(p->zdec, tilebuf, tilesize, size);
			if(ret) return ret;
		}

		//イメージセット

		(func)(p->img, tilebuf,
			pl->offx + (pos % tilew) * 64, pl->offy + (pos / tilew) * 64,
			pl->col, pl->texitem);
	}

	return MLKERR_OK;
}

/** レイヤイメージ合成 */

static mlkerr _blend_layer(mImageBuf2 *img,LayerData *pl,int opacity,void *ptr)
{
	APDv2Data *p = (APDv2Data *)ptr;
	FILE *fp;
	uint8_t *tilebuf;
	uint32_t pos,size,tilesize,i;
	int tilew;
	func_blendtile func;
	mlkerr ret;

	fseeko(p->fp, pl->fpos, SEEK_SET);

	fp = p->fp;
	tilebuf = p->tilebuf;
	tilew = pl->tilew;
	tilesize = g_tilesize_tbl[pl->coltype];
	func = g_funcs_blendtile[pl->coltype];

	for(i = pl->imgparam; i; i--)
	{
		//タイル情報
		
		if(mFILEreadFormatBE(fp, "ii", &pos, &size)
			|| size > tilesize)
			return MLKERR_DAMAGED;

		//タイル読み込み

		if(size == tilesize)
		{
			if(fread(tilebuf, 1, tilesize, fp) != tilesize)
				return MLKERR_DAMAGED;
		}
		else
		{
			mZlibDecReset(p->zdec);

			ret = mZlibDecReadOnce(p->zdec, tilebuf, tilesize, size);
			if(ret) return ret;
		}

		//合成

		(func)(img, tilebuf,
			pl->offx + (pos % tilew) * 64, pl->offy + (pos / tilew) * 64,
			pl->blendmode, opacity, pl->col, pl->texitem);
	}

	return MLKERR_OK;
}

/** レイヤ情報読み込み
 *
 * [!] 上層のレイヤから順に並んでいる */

static mlkerr _read_layerinfo(FILE *fp,APDv2Data *p,int layernum)
{
	LayerData *pl;
	char *name;
	uint8_t tflags,coltype,opacity,blendmode,amask,is_img;
	uint16_t parent,tilew,tileh;
	uint32_t col,flags,tilenum;
	int32_t offx,offy;
	mlkerr ret;

	pl = p->layer;

	for(; layernum; layernum--, pl++)
	{
		//親のレイヤ位置 (0xfffe で終了、0xffff でルート)

		if(mFILEreadBE16(fp, &parent))
			return MLKERR_DAMAGED;

		if(parent == 0xfffe) break;

		//フラグ (bit0:フォルダ、bit1:カレントレイヤ)

		if(mFILEreadByte(fp, &tflags))
			return MLKERR_DAMAGED;

		is_img = !(tflags & 1);

		//レイヤ名

		if(mFILEreadStr_variable(fp, &name) < 0)
			return MLKERR_DAMAGED;

		if(name)
		{
			pl->name = add_name_utf8(name, -1);
			mFree(name);
		}

		//レイヤ情報

		if(mFILEreadFormatBE(fp, "bbbbii", &coltype, &opacity, &blendmode, &amask, &col, &flags)
			|| coltype > 3)
			return MLKERR_DAMAGED;

		if(blendmode >= 17)
			blendmode = BLENDMODE_NORMAL;

		//イメージ情報

		if(is_img)
		{
			if(mFILEreadFormatBE(fp, "iihhi",
				&offx, &offy, &tilew, &tileh, &tilenum))
				return MLKERR_DAMAGED;
		}

		//情報セット

		pl->parent = parent;
		pl->opacity = opacity;
		pl->coltype = coltype;
		pl->blendmode = blendmode;
		pl->col = col;

		if(is_img)
		{
			pl->fpos = ftello(fp);
			pl->imgparam = tilenum;
			pl->offx = offx;
			pl->offy = offy;
			pl->tilew = tilew;
			pl->tileh = tileh;
		}
		
		if(!is_img) pl->flags |= LAYER_FLAGS_FOLDER;
		if(!(flags & 1)) pl->flags |= LAYER_FLAGS_HIDE;

		//タイルスキップ

		if(is_img)
		{
			ret = _skip_tiles(fp, tilenum);
			if(ret) return ret;
		}
	}

	return MLKERR_OK;
}

/** レイヤ読み込み */

static mlkerr _read_layer(FILE *fp,APDv2Data *p)
{
	uint16_t layernum;
	mlkerr ret;

	//レイヤ数

	if(mFILEreadBE16(fp, &layernum))
		return MLKERR_DAMAGED;

	printf(" (%dx%d) layer:%d, %d dpi\n", p->w, p->h, layernum, g_work.src_dpi);

	//レイヤデータ

	p->layer = (LayerData *)mMalloc0(sizeof(LayerData) * layernum);
	if(!p->layer) return MLKERR_ALLOC;

	//レイヤ情報読み込み

	ret = _read_layerinfo(fp, p, layernum);
	if(ret) return ret;

	//確保

	if(ISNOT_PROC_INFO)
	{
		//レイヤイメージ
		
		if(IS_PROC_LAYER)
		{
			p->img = mImageBuf2_new(p->w, p->h, 32, 0);
			if(!p->img) return MLKERR_ALLOC;
		}

		//タイルバッファ

		p->tilebuf = (uint8_t *)mMalloc(64 * 64 * 2 * 4);
		if(!p->tilebuf) return MLKERR_ALLOC;
	}

	//処理

	switch(g_work.proctype)
	{
		case PROCTYPE_BLEND:
			return output_blendimage_tile(p->w, p->h, p->layer, layernum, _blend_layer, p, 48);

		case PROCTYPE_LAYER:
			return output_layers(p->img, p->layer, layernum, _read_layer_image, p);

		case PROCTYPE_INFO:
			put_layerinfo(p->layer, layernum);
			break;
	}

	return MLKERR_OK;
}

/** 読み込みメイン */

static mlkerr _main_proc(FILE *fp,APDv2Data *p)
{
	uint8_t sig,finfo = 0;
	uint32_t size;
	uint16_t imgw,imgh,dpi;
	mlkerr ret;

	while(mFILEreadByte(fp, &sig) == 0)
	{
		if(sig == 'L')
		{
			//---- レイヤ

			if(!finfo) return MLKERR_INVALID_VALUE;

			ret = _read_layer(fp, p);
			if(ret) return ret;
		}
		else
		{
			if(mFILEreadBE32(fp, &size))
				return MLKERR_DAMAGED;

			if(sig == 'I' && !finfo)
			{
				//イメージ情報

				if(mFILEreadFormatBE(fp, "hhh", &imgw, &imgh, &dpi))
					return MLKERR_DAMAGED;

				p->w = imgw;
				p->h = imgh;

				g_work.src_dpi = dpi;
			
				finfo = 1;
				size -= 6;
			}

			if(fseek(fp, size, SEEK_CUR))
				return MLKERR_DAMAGED;
		}
	}

	return MLKERR_OK;
}

/** APD v2 読み込み (BigEndian) */

mlkerr load_apd_v2(FILE *fp)
{
	APDv2Data dat;
	mlkerr ret;

	mMemset0(&dat, sizeof(APDv2Data));
	dat.fp = fp;

	//zlib

	if(ISNOT_PROC_INFO)
	{
		dat.zdec = mZlibDecNew(64 * 64 * 2 * 4, MZLIB_WINDOWBITS_ZLIB);
		if(!dat.zdec) return MLKERR_UNKNOWN;

		mZlibSetIO_stdio(dat.zdec, fp);
	}

	//

	ret = _main_proc(fp, &dat);

	//

	mZlibFree(dat.zdec);
	mImageBuf2_free(dat.img);
	mFree(dat.tilebuf);
	mFree(dat.layer);

	return ret;
}
