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

/*****************************************
 * ADW ver 2 読み込み
 *****************************************/

#include <stdio.h>

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

#include "def.h"


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

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

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


/** タイルイメージを RGBA にセット */

static void _set_tileimage(ADWv2Data *p,int x,int y,uint32_t col)
{
	mRect rc;
	int ix,iy,w,xtop,pitchs;
	uint8_t *ps,*pd,**ppd,r,g,b;

	//イメージ範囲内にクリッピング

	rc.x1 = x, rc.y1 = y;
	rc.x2 = x + 63, rc.y2 = y + 63;

	if(!mRectClipBox_d(&rc, 0, 0, p->w, p->h))
		return;

	//

	ps = p->tilebuf + (rc.y1 - y) * 64 + (rc.x1 - x);
	ppd = p->img->ppbuf + rc.y1;
	w = rc.x2 - rc.x1 + 1;
	xtop = rc.x1 * 4;
	pitchs = 64 - w;

	r = MLK_RGB_R(col);
	g = MLK_RGB_G(col);
	b = MLK_RGB_B(col);

	for(iy = rc.y2 - rc.y1 + 1; iy; iy--, ppd++)
	{
		pd = *ppd + xtop;
		
		for(ix = w; ix; ix--, pd += 4)
		{
			pd[0] = r;
			pd[1] = g;
			pd[2] = b;
			pd[3] = *(ps++);
		}

		ps += pitchs;
	}
}

/** レイヤイメージ読み込み */

static mlkerr _read_layer_image(LayerData *pl,void *ptr)
{
	ADWv2Data *p = (ADWv2Data *)ptr;
	FILE *fp;
	uint8_t *tilebuf;
	uint16_t tx,ty,size;
	uint32_t i;
	mlkerr ret;

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

	image_fill_zero(p->img);

	fp = p->fp;
	tilebuf = p->tilebuf;

	//

	for(i = pl->imgparam; i; i--)
	{
		//タイル情報
		
		if(mFILEreadFormatLE(fp, "hhh", &tx, &ty, &size)
			|| size == 0
			|| size > 4096)
			return MLKERR_DAMAGED;

		//タイル読み込み

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

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

		//イメージセット

		_set_tileimage(p, pl->offx + tx * 64, pl->offy + ty * 64, pl->col);
	}

	return MLKERR_OK;
}

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

static mlkerr _skip_tiles(FILE *fp,uint32_t tilenum)
{
	uint16_t tx,ty,size;

	for(; tilenum; tilenum--)
	{
		if(mFILEreadFormatLE(fp, "hhh", &tx, &ty, &size)
			|| fseek(fp, size, SEEK_CUR))
			return MLKERR_DAMAGED;
	}

	return MLKERR_OK;
}

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

static mlkerr _read_layerinfo(FILE *fp,ADWv2Data *p,int layernum,int layerinfo_seek)
{
	LayerData *pl;
	uint16_t name[25];
	int32_t x1,y1,x2,y2;
	uint32_t col,tilenum;
	uint8_t opacity,flags;
	char *strbuf;
	mlkerr ret;

	pl = p->layer + layernum - 1;

	for(; layernum; layernum--, pl--)
	{
		//レイヤ情報

		if(mFILEreadFormatLE(fp, "iiiii", &x1, &y1, &x2, &y2, &tilenum)
			|| mFILEreadArrayLE16(fp, name, 25) != 25
			|| mFILEreadFormatLE(fp, "bib", &opacity, &col, &flags)
			|| fseek(fp, 3 + layerinfo_seek, SEEK_CUR))
			return MLKERR_DAMAGED;
	
		//レイヤ名 (UTF-16 -> UTF-8)

		strbuf = mUTF16toUTF8_alloc(name, 24, NULL);
		if(strbuf)
		{
			pl->name = add_name_utf8(strbuf, -1);
			mFree(strbuf);
		}

		//セット

		pl->fpos = ftello(fp);
		pl->parent = 0xffff;
		pl->opacity = opacity;
		pl->col = col;
		pl->offx = x1;
		pl->offy = y1;
		pl->imgparam = tilenum;

		if(!(flags & 1)) pl->flags |= LAYER_FLAGS_HIDE;

		//スキップ

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

	return MLKERR_OK;
}

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

static mlkerr _main_proc(FILE *fp,ADWv2Data *p)
{
	uint32_t size;
	uint16_t wsize,imgw,imgh,dpi,layernum,layersel,layerinfosize;
	mlkerr ret;

	//プレビューイメージをスキップ

	if(fseek(fp, 4, SEEK_CUR)	//w, h
		|| mFILEreadLE32(fp, &size)
		|| fseek(fp, size, SEEK_CUR))
		return MLKERR_DAMAGED;

	//メイン情報

	if(mFILEreadFormatLE(fp, "hhhhhhh",
			&wsize, &imgw, &imgh, &dpi, &layernum, &layersel, &layerinfosize)
		|| fseek(fp, wsize - 12, SEEK_CUR))
		return MLKERR_DAMAGED;

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

	g_work.src_dpi = dpi;

	printf(" (%dx%d) layer:%d, %d dpi\n", imgw, imgh, layernum, dpi);

	//レイヤデータ

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

	//レイヤ情報読み込み

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

	//確保
	
	if(ISNOT_PROC_INFO)
	{
		//レイヤイメージ

		p->img = mImageBuf2_new(imgw, imgh, 32, 0);
		if(!p->img) return MLKERR_ALLOC;

		//タイル用バッファ

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

	//処理

	switch(g_work.proctype)
	{
		case PROCTYPE_BLEND:
			return output_blendimage8(imgw, imgh, p->img,
				p->layer, layernum, _read_layer_image, p);

		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;
}

/** ADW v2 読み込み */

mlkerr load_adw_v2(FILE *fp)
{
	ADWv2Data dat;
	mlkerr ret;

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

	//zlib

	if(ISNOT_PROC_INFO)
	{
		dat.zdec = mZlibDecNew(4096, 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;
}
