/*<<<***************************************************************************
The MIT License (MIT)

Copyright(C) 2013 - 2015 Marc Mirti Mancinelli, Christophe Lardau and Philippe Pamart (xdcube.org)

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.
////////////////////////////////////////////////////////////////////////////////
#Title: gdiItf
#Project: xdcGdi
////////////////////////////////////////////////////////////////////////////////
#Author: Marc MIRTI MANCINELLI
#History:
<14/09/2013: creation.
12/02/2014: this notice inserted.
***************************************************************************>>>*/
#include "stdafx.h"
#include "gdiItf.h"
#include "_gdiVer.h"
#include "gdiImage.h"
#include <xbColor.h>

xbEimpl( gdiEcompress, xbEadv );
xbEimpl( gdiEcompressUser, gdiEcompress );

gdiCompressPlugType	g_gdiCompressPlugType("Picture",XDCGDI_PLUGSVER,"XDCUBE HotPlug Picture Compression");

bool	gdiCompressPlugType::CreatePluggedObject(const xbString &name,xbRefPtr<IgdiCompressPlug> *pprObj,xbRefPtr<IxbHotPlugin> *pprPlugin)
{
	xbRefPtr<IxbObject> prObj;
	if (CreatePluggedObject(name,pprObj?&prObj:NULL,pprPlugin))
	{
		if (pprObj)
		{
			*pprObj = xbRefQIPtr<IgdiCompressPlug>(prObj);
		}
		return true;
	}
/*	if (name.CompareNoCase("eplz") == 0 || name.CompareNoCase("eplzss") == 0)
	{
		if (pprPlugin)
			pprPlugin->Empty();
		if (!pprObj)
			return true;

		xbLZSSplug *plg = xbDnew xbLZSSplug();
		if (!plg) xbThrow CMemoryException();
		try
		{
	//		plg->setFactory(pFactory);
			plg->Create();

			(*pprObj) = plg;

			plg->Release();
		}
		catch(...)
		{
			plg->Release();
			throw;
		}
		return true;
	}*/
	return false;
}

bool	gdiCompressPlugType::CreatePluggedObject(const xbString &name,xbRefPtr<IxbObject> *pprObj,xbRefPtr<IxbHotPlugin> *pprPlugin)
{
	xbLock lckStart(this);
	loadConfig();

	xbString plgname;
	xbRefPtr<Plugin>	pPlg;
	{
		xbSectLock lck(&m_sect);
		Object *pObj = m_arrObj.SortedFind(&name,findPlugObj);
		if (pObj)
		{
			plgname = pObj->m_name;
			plgname.OwnData();
			pPlg = pObj->m_pPlg;
			goto found;
		}
		pObj = m_arrObj.Begin();
		Object *pEnd = m_arrObj.End();
		while(pObj < pEnd)
		{
			xbArray<xbString> arrName;
			pObj->m_name.Split('.',&arrName);

			xbString *pSname = arrName.Begin();
			xbString *pSnameEnd = arrName.End();
			while(pSname < pSnameEnd)
			{
				if (pSname->CompareNoCase(name) == 0)
				{
					plgname = pObj->m_name;
					plgname.OwnData();
					pPlg = pObj->m_pPlg;
					goto found;
				}
				pSname++;
			}

			pObj++;
		}

		return false;
	}

found:
	pPlg->createPluggedObject(plgname,pprObj,pprPlugin,NULL);

	return true;
}
int		gdiCompressPlugType::PrioritySort(const Object &obj1,const Object &obj2)
{
	if (obj1.m_priority > obj2.m_priority)
		return 1;
	if (obj1.m_priority < obj2.m_priority)
		return -1;
	return obj1.m_name.CompareNoCase(obj2.m_name);
}

int		gdiCompressPlugType::GetSupportedType(xbArray<xbString> *pArrEncode)
{
	xbLock lckStart(this);
	loadConfig();

	xbArray<Object>	arrObj;
//	bool bEPLZSS = false;
	{
		xbSectLock lck(&m_sect);
		Object *pObj = m_arrObj.Begin();
		Object *pEnd = m_arrObj.End();
		while(pObj < pEnd)
		{
			xbString name(pObj->m_name);
			name.OwnData();
//			if (name.CompareNoCase("eplzss") == 0)
//				bEPLZSS = true;
			arrObj.Add(Object(name,pObj->m_priority,NULL,NULL));
			pObj++;
		}
	}
//	if (!bEPLZSS)
//		arrObj.Add(Object("eplzss",0x10000,NULL,NULL));
	if (pArrEncode)
	{
		arrObj.Sort(PrioritySort);
		pArrEncode->Length = arrObj.Length;
		xbString *pStr = pArrEncode->Begin();
		Object *pObj = arrObj.Begin();
		Object *pEnd = arrObj.End();
		while(pObj < pEnd)
		{
			*pStr = pObj->m_name;
			pObj++;
			pStr++;
		}
	}

	return arrObj.Length;
}

int		gdiCompressPlugType::GetSupportedType(xbArray<gdiCompressPlugInfo> *pArrType,gdiCompressCaps caps,bool bGetPlugRef,LCID lcid)
{
	xbLock lckStart(this);
	xbArray<xbString> arrTypes;
	GetSupportedType(&arrTypes);

	pArrType->Length = arrTypes.Length; 
	int j = 0;
	for(int i = 0; i<arrTypes.Length; i++)
	{
		xbString &type = arrTypes.GetAt(i);
		xbRefPtr<IgdiCompressPlug>	prPlg;
		if (!CreatePluggedObject(type,&prPlg))
			continue;
		if (caps != gdiCompressCaps_None && !(caps & prPlg->GetCaps()))
			continue;
		gdiCompressPlugInfo &info = pArrType->GetAt(j++);
		if (bGetPlugRef)
			info.prPlug = prPlg;

		info.typeVersion = prPlg->GetCompressVersion(true,lcid);
		if (type.CompareNoCase("default")==0)
		{
			info.typeLabel = "default";
			info.extensions = prPlg->GetDefaultExtension();
			continue;
		}
		info.typeLabel = prPlg->GetCompressLabel(true,lcid);
		info.typeVersion = prPlg->GetCompressVersion(true,lcid);

		int pos=0;
		xbString ext;
		while((pos = type.GetToken(pos,".",&ext))>0)
		{
			if (info.extensions.IsValid())
				info.extensions += ";";
			info.extensions += "*."+ext;
		}
	}
	pArrType->Length = j;
	return j;
}


xbString gdiCompressPlugType::GetImageFileFilter(xbString *pDfltExt,gdiCompressCaps caps,LCID lcid)
{
	xbArray<gdiCompressPlugInfo> arrInfo;
	g_gdiCompressPlugType.GetSupportedType(&arrInfo,caps,false,lcid);

	int cnt = 0;
	xbString ret,allext;
	for(int i = 0;i<arrInfo.Length;i++)
	{
		gdiCompressPlugInfo &info = arrInfo.GetAt(i);
		if (info.typeLabel.CompareNoCase("default") == 0)
		{
			if (pDfltExt)
				*pDfltExt = "."+info.extensions;
			continue;
		}

		ret += info.typeLabel+" ("+info.extensions+")|"+info.extensions+"|";
		if (allext.IsValid())
			allext += ";";
		allext += info.extensions;
		cnt++;
	}

	if (ret.IsEmpty())
		return "No plugins available|*.*||";

	if (cnt > 1)
	{
		if ((caps & gdiCompressCaps_ReadWrite) != gdiCompressCaps_Write)
			ret = "All supported images ("+allext+")|"+allext+"|"+ret;
		else
			ret += "All supported images ("+allext+")|"+allext+"|";
	}

	return ret+"|";
/*	if (pDfltExt)
		*pDfltExt = ".jpg";

	return "JPEG images|*.jpg;*.jpeg||";
	*/
}
/*
gdiMetricSize gdiMetricSize::ToUnit(gdiMetricUnit unit, IgdiDC *pDC) const
{
	if (IsEmpty())
		return *this;

	if (unit == unitX && unit == unitY)
		return *this;

	xbThrow gdiEcompress(E_NOTIMPL,"gdiMetricSize::ToUnit() : conversions not implemented (xdcGdi)");
}
*/
bool gdiCreateImage(xbRefPtr<IgdiImage> *pprImg,LPCSTR pType, LPCSTR pLabel, xbOpMode reqMode)
{
	gdiImage *plg = xbDnew gdiImage();
	try
	{
		plg->setParams(pType,pLabel);
		plg->Create();
		
		(*pprImg) = plg;
		
		plg->Release();
	}
	catch(...)
	{
		plg->Release();
		throw;
	}
	return true;
}

bool gdiCreateBitmap(xbRefPtr<IgdiBitmap> *pprBmp, const gdiSizeLow &sz, gdiBmpColorType bmpType, int bitsPerPixel, xbOpMode reqMode)
{
	gdiBitmap *plg = xbDnew gdiBitmap();
	try
	{
		if (!plg->setParams(sz,bmpType,bitsPerPixel,reqMode))
			return false;

		plg->Create();
		
		(*pprBmp) = plg;
		
		plg->Release();
	}
	catch(...)
	{
		plg->Release();
		throw;
	}
	return true;
}

bool	gdiCompressPlugType::CanWorkWith(IxbHotPlugin *pObj,const xbString &name)
{
	if (xbHotPlugType::CanWorkWith(pObj,name))
		return true;
//	if (!pObj && (name.CompareNoCase("eplz") == 0 || name.CompareNoCase("eplzss") == 0))
//		return true;
	return false;
}

bool	gdiCompressPlugType::CanWorkWithType(LPCSTR pszType, IxbInputStream *pStm, xbRefPtr<IgdiDecompressor> *pprDecomp, IgdiImage *pImg)
{
	xbLock lckStart(this);
	xbArray<xbString> arrTypes;
	GetSupportedType(&arrTypes);

	for(int i = 0; i<arrTypes.Length; i++)
	{
		xbRefPtr<IgdiCompressPlug>	prPlg;
		if (!CreatePluggedObject(arrTypes.GetAt(i),&prPlg))
			continue;
		
		if (prPlg->CanWorkWithType(pszType,pStm,pprDecomp,pImg))
			return true;
	}

	return false;
}

bool	gdiCompressPlugType::CanWorkWithType(LPCSTR pszType,const uchar *pStmData, int lgData, int *pLgDataMin, xbRefPtr<IgdiDecompressor> *pprDecomp, IgdiImage *pImg)
{
	xbLock lckStart(this);
	xbArray<xbString> arrTypes;
	GetSupportedType(&arrTypes);

	for(int i = 0; i< arrTypes.Length; i++)
	{
		xbRefPtr<IgdiCompressPlug>	prPlg;
		if (!CreatePluggedObject(arrTypes.GetAt(i),&prPlg))
			continue;

		int lgDataMin = -1;
		if (prPlg->CanWorkWithType(pszType,pStmData,lgData,&lgDataMin,pprDecomp,pImg))
		{
			return true;
		}
		if (lgDataMin > 0)
		{
			*pLgDataMin = lgDataMin;
			return false;
		}
	}

	return false;
}
