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

/*****************************************
 * PSD 書き込み (mSaveImage)
 *****************************************/

#include "mlk.h"
#include "mlk_saveimage.h"
#include "mlk_psd.h"
#include "mlk_util.h"


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

typedef struct
{
	mPSDSave *psd;
	uint8_t *rowbuf;
}psdsave;

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


/** ヘッダ書き込み */

static int _write_header(mPSDSave *psd,mSaveImage *si)
{
	mPSDHeader hd;

	hd.width = si->width;
	hd.height = si->height;
	hd.bits = si->bits_per_sample;
	hd.img_channels = si->samples_per_pixel;

	switch(si->coltype)
	{
		//GRAY
		case MSAVEIMAGE_COLTYPE_GRAY:
			hd.colmode = (hd.bits == 1)?
				MPSD_COLMODE_MONO: MPSD_COLMODE_GRAYSCALE;
			break;
		//RGB
		case MSAVEIMAGE_COLTYPE_RGB:
			hd.colmode = MPSD_COLMODE_RGB;
			break;
		//CMYK
		case MSAVEIMAGE_COLTYPE_CMYK:
			hd.colmode = MPSD_COLMODE_CMYK;
			break;
	}

	return mPSDSave_writeHeader(psd, &hd);
}

/** リソース書き込み */

static int _write_resource(mPSDSave *psd,mSaveImage *si,mSaveOptPSD *opt)
{
	int h,v;

	//解像度

	if(mSaveImage_getDPI(si, &h, &v))
		mPSDSave_res_setResoDPI(psd, h, v);

	//ICC プロファイル

	if(opt && (opt->mask & MSAVEOPT_PSD_MASK_ICCPROFILE))
	{
		if(!mPSDSave_res_setICCProfile(psd, opt->profile_buf, opt->profile_size))
			return MLKERR_ALLOC;
	}

	//書き込み

	return mPSDSave_writeResource(psd);
}

/** イメージ書き込み */

static int _write_image(psdsave *p,mSaveImage *si)
{
	mPSDSave *psd = p->psd;
	uint8_t *rowbuf;
	int ret,ich,iy,pitch,height,conv,bits;
	int last_prog,new_prog,prog_max,prog_cnt;
	mFuncSaveImageProgress progress;

	pitch = mPSDSave_getImageRowSize(psd);
	bits = si->bits_per_sample;

	//バッファ確保 (1ch)

	rowbuf = (uint8_t *)mMalloc(pitch);
	if(!rowbuf) return MLKERR_ALLOC;

	p->rowbuf = rowbuf;
	
	//開始

	ret = mPSDSave_startImage(psd);
	if(ret) return ret;

	//変換

	if(bits == 1)
		conv = 1;
	else if(si->coltype == MSAVEIMAGE_COLTYPE_CMYK)
		conv = (bits == 16)? 3: 2;
	else
		conv = 0;

	//イメージ

	progress = si->progress;
	height = si->height;
	last_prog = 0;
	prog_cnt = 1;
	prog_max = height * si->samples_per_pixel;

	for(ich = 0; ich < si->samples_per_pixel; ich++)
	{
		for(iy = 0; iy < height; iy++)
		{
			ret = (si->setrow_ch)(si, iy, ich, rowbuf, pitch);
			if(ret) return ret;

			//変換

			if(conv == 1)
				//1bit: ビット反転
				mReverseBit(rowbuf, pitch);
			else if(conv == 2)
				//CMYK 8bit: 値反転
				mReverseVal_8bit(rowbuf, pitch);
			else if(conv == 3)
				//CMYK 16bit: 値反転
				mReverseVal_16bit(rowbuf, pitch >> 1);

			//16bit LE -> BE

		#if !defined(MLK_BIG_ENDIAN)
			if(bits == 16)
				mSwapByte_16bit(rowbuf, pitch >> 1);
		#endif

			//書き込み

			ret = mPSDSave_writeImageRowCh(psd, rowbuf);
			if(ret) return ret;

			//経過

			if(progress)
			{
				new_prog = prog_cnt * 100 / prog_max;
				prog_cnt++;

				if(new_prog != last_prog)
				{
					(progress)(si, new_prog);
					last_prog = new_prog;
				}
			}
		}
	}

	//終了

	return mPSDSave_endImage(psd);
}

/** メイン処理 */

static int _main_proc(psdsave *p,mSaveImage *si,mSaveOptPSD *opt)
{
	mPSDSave *psd;
	int ret;

	//psd

	psd = mPSDSave_new();
	if(!psd) return MLKERR_ALLOC;

	p->psd = psd;

	//開く

	switch(si->open.type)
	{
		case MSAVEIMAGE_OPEN_FILENAME:
			ret = mPSDSave_openFile(psd, si->open.filename);
			break;
		case MSAVEIMAGE_OPEN_FP:
			ret = mPSDSave_openFILEptr(psd, si->open.fp);
			break;
		default:
			ret = MLKERR_OPEN;
			break;
	}

	if(ret) return ret;

	//圧縮タイプを無圧縮に

	if(opt
		&& (opt->mask & MSAVEOPT_PSD_MASK_COMPRESSION)
		&& opt->compression == 0)
		mPSDSave_setCompression_none(psd);

	//ヘッダ書き込み

	ret = _write_header(psd, si);
	if(ret) return ret;

	//リソース

	ret = _write_resource(psd, si, opt);
	if(ret) return ret;

	//レイヤなし

	ret = mPSDSave_writeLayerNone(psd);
	if(ret) return ret;

	//イメージ

	return _write_image(p, si);
}


//========================


/**@ PSD 保存 */

mlkerr mSaveImagePSD(mSaveImage *si,void *opt)
{
	psdsave dat;
	int ret;

	mMemset0(&dat, sizeof(psdsave));

	ret = _main_proc(&dat, si, (mSaveOptPSD *)opt);

	//

	mPSDSave_close(dat.psd);

	mFree(dat.rowbuf);

	return ret;
}
