/*$
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 ver1 読み込み
 *****************************************/

#include <stdio.h>

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

#include "def.h"


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

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

/* 合成モード変換テーブル */

static const uint8_t g_v1_blendmode[] = {
	BLENDMODE_NORMAL, BLENDMODE_MUL, BLENDMODE_LUM_ADD, BLENDMODE_LUM_SUB,
	BLENDMODE_SCREEN, BLENDMODE_OVERLAY, BLENDMODE_SOFT_LIGHT, BLENDMODE_HARD_LIGHT,
	BLENDMODE_DODGE, BLENDMODE_BURN, BLENDMODE_LINEAR_BURN, BLENDMODE_VIVID_LIGHT,
	BLENDMODE_LINEAR_LIGHT, BLENDMODE_PIN_LIGHT, BLENDMODE_DIFF,
	BLENDMODE_LIGHTEN, BLENDMODE_DARKER,
	BLENDMODE_HUE, BLENDMODE_SATURATION, BLENDMODE_COLOR, BLENDMODE_LUM
};

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


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

static mlkerr _read_layer_image(LayerData *pl,void *ptr)
{
	APDv1Data *p = (APDv1Data *)ptr;
	uint8_t **ppbuf;
	int i,pitch;
	mlkerr ret;

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

	ppbuf = p->img->ppbuf + p->h - 1;
	pitch = p->w * 4;

	mZlibDecReset(p->zdec);
	mZlibDecSetSize(p->zdec, pl->imgparam);

	for(i = p->h; i; i--, ppbuf--)
	{
		ret = mZlibDecRead(p->zdec, *ppbuf, pitch);
		if(ret) return ret;

		//BGRA -> RGBA
		mImageConv_swap_rb_8(*ppbuf, p->w, 4);
	}

	return mZlibDecFinish(p->zdec);
}

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

static mlkerr _read_layer_info(FILE *fp,APDv1Data *p,int layernum,int layerinfo_seek)
{
	LayerData *pl;
	char name[32];
	uint32_t size;
	uint8_t blendmode,opacity,flags;

	pl = p->layer + layernum - 1;

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

		if(fread(name, 1, 32, fp) != 32
			|| mFILEreadFormatLE(fp, "bbb", &blendmode, &opacity, &flags)
			|| fseek(fp, layerinfo_seek, SEEK_CUR)
			|| mFILEreadLE32(fp, &size))	//イメージ圧縮サイズ
			return MLKERR_DAMAGED;

		//レイヤ名

		name[31] = 0;
		pl->name = add_name_checkcode(name, -1);

		//合成モード

		if(blendmode >= 21)
			blendmode = BLENDMODE_NORMAL;
		else
			blendmode = g_v1_blendmode[blendmode];

		//セット

		pl->fpos = ftello(fp);
		pl->parent = 0xffff;
		pl->blendmode = blendmode;
		pl->opacity = opacity;
		pl->imgparam = size;

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

		//イメージスキップ

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

	return MLKERR_OK;
}

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

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

	//メイン情報

	if(mFILEreadFormatLE(fp, "ihhhhh",
		&size, &imgw, &imgh, &layernum, &layercnt, &layersel))
		return MLKERR_DAMAGED;
	
	fseek(fp, size - 10, SEEK_CUR);

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

	//情報表示

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

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

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

	//レイヤ情報サイズ

	if(mFILEreadLE32(fp, &layerinfosize))
		return MLKERR_DAMAGED;

	//レイヤデータ

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

	//レイヤ情報読み込み

	ret = _read_layer_info(fp, p, layernum, layerinfosize - 35);
	if(ret) return ret;

	//レイヤイメージ

	if(ISNOT_PROC_INFO)
	{
		p->img = mImageBuf2_new(imgw, imgh, 32, 0);
		if(!p->img) 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;
}

/** APD v1 読み込み */

mlkerr load_apd_v1(FILE *fp)
{
	APDv1Data dat;
	mlkerr ret;

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

	g_work.src_dpi = 0;

	//zlib

	if(ISNOT_PROC_INFO)
	{
		dat.zdec = mZlibDecNew(16 * 1024, 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.layer);

	return ret;
}
