/*******************************************************************************
  TPI - flexible but useless plug-in framework.
  Copyright (C) 2002-2009 Silky

  This library is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the Free
  Software Foundation; either version 2.1 of the License, or (at your option)
  any later version.

  This library is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  for more details.

  You should have received a copy of the GNU Lesser General Public License along
  with this library; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

  $Id: spiLibrary.cpp 340 2010-09-23 14:53:19Z sirakaba $
*******************************************************************************/

//******************************************************************************
//    Includes
//******************************************************************************

#include "../../common/header/plugin.h"
#include "../../common/header/plugin-extra.h"
#include "../../common/library/library.h"
#include <wx/file.h>
#include <wx/stdpaths.h>
#include <wx/dir.h>
#include <windows.h>
#include "spiLibrary.h"

//******************************************************************************
//    Global varients
//******************************************************************************

HMODULE g_hLib;
TPI_PROC g_prProc;

//******************************************************************************
//    Callback Wrapper
//******************************************************************************

int __stdcall CallbackProc(int _nNow, int, long _lData)
{
	// 構造体を初期化。
	TPI_PROCESSINFO * piInfo = (TPI_PROCESSINFO *) _lData;
	piInfo->nProcessedSize = _nNow;

	// コールバック関数に送信。
	return g_prProc != NULL && g_prProc(TPI_NOTIFY_COMMON, piInfo) == TPI_CALLBACK_CANCEL;
}

//******************************************************************************
//    Inside Functions
//******************************************************************************

int ErrorCodeConvert(int nErrorCode)
{
	switch (nErrorCode)
	{
	case -1: return TPI_ERROR_U_USE_LIBRARY;
	case 0:  return TPI_ERROR_SUCCESS;
	case 1:  return TPI_ERROR_D_SKIPPED;
	case 2:  return TPI_ERROR_ARC_UNSUPPORTED;
	case 3:  return TPI_ERROR_ARC_BROKEN_MISC;
	case 4:  return TPI_ERROR_D_OUTOFMEMORY;
	case 5:  return TPI_ERROR_D_USEMEMORY;
	case 6:  return TPI_ERROR_IO_ARC_READ;
	default: return TPI_ERROR_UNDEFINED;
	}
}

//******************************************************************************
//    Functions
//******************************************************************************

#ifdef __cplusplus
extern "C"
{
#endif

int __stdcall GetPluginInformation
(
	unsigned int _uInfoId,
	wxULongLong_t,
	void * _pPtr
)
{
	if (_pPtr == NULL)
	{
		return TPI_ERROR_D_PARAMETER;
	}
	switch (_uInfoId)
	{
	case TPI_INFO_VERSION_MAJOR:
	case TPI_INFO_VERSION_MINOR:
		* (int *) _pPtr = 0;
		break;
	case TPI_INFO_VERSION_API:
		* (int *) _pPtr = 2;
		break;
	default:
		return TPI_ERROR_D_PARAMETER;
	}
	return TPI_ERROR_SUCCESS;
}

int __stdcall GetFormatInformation(TPI_FORMATINFO *, bool)
{
	return TPI_ERROR_D_UNSUPPORTED;
}

int __stdcall LoadPlugin
(
	const wxString & _szArcName,
	wxULongLong_t
)
{
	// ファイルを開く。
	wxFile hFile;
	if (! hFile.Exists(_szArcName) || ! hFile.Open(_szArcName, wxFile::read))
	{
		return TPI_ERROR_IO_ARC_OPEN;
	}

	// 最初の2KBを読み込み。
	char buffer[2050];
	::ZeroMemory(buffer, sizeof(buffer));
	if (hFile.Read(buffer, sizeof(buffer)) == wxInvalidOffset)
	{
		hFile.Close();
		return TPI_ERROR_IO_ARC_READ;
	}
	hFile.Close();

	wxStandardPaths p;
	wxString szSPIPath = wxPathOnly(p.GetExecutablePath()) + wxT("/lib/"), szSPIName;
	wxDir fs(szSPIPath);
	if (fs.GetFirst(& szSPIName, wxT("*.spi")))
	{
		do
		{
			// SPIをロード。
			g_hLib = ::LoadLibrary((szSPIPath + szSPIName).wchar_str());
			if (g_hLib == NULL)
			{
				continue;
			}

			// GetPluginInfoを実行。
			FARPROC	fpProc = ::GetProcAddress(g_hLib, "GetPluginInfo");
			char szPluginType[5]; // 種類4bytes + NULL
			if (fpProc == NULL
				|| ((int (PASCAL *)(int, char *, int)) fpProc)(0, szPluginType, sizeof(szPluginType)) <= 0
				|| szPluginType[2] != 'A' || szPluginType[3] != 'M')
			{
				::FreeLibrary(g_hLib);
				continue;
			}

			// 書庫に対応しているかチェック。
			fpProc = ::GetProcAddress(g_hLib, "IsSupported");
			if (fpProc == NULL)
			{
				::FreeLibrary(g_hLib);
				continue;
			}

			if (((BOOL (PASCAL *)(const char *, unsigned long)) fpProc)(_szArcName.ToUTF8(), (unsigned long) buffer))
			{
				// 対応していれば処理を終了。
				return TPI_ERROR_SUCCESS;
			}
		}
		while (fs.GetNext(& szSPIName));
	}
	return TPI_ERROR_U_LOAD_LIBRARY;
}

int __stdcall FreePlugin
(
	void * // _pReserved
)
{
	::FreeLibrary(g_hLib);
	return TPI_ERROR_SUCCESS;
}

int __stdcall OpenArchive
(
	const wxString & _szArcName,
	void * * _hArchive,
	wxULongLong_t * _nFileCount
)
{
	FARPROC fpProc = ::GetProcAddress(g_hLib, "GetArchiveInfo");
	if (fpProc == NULL)
	{
		return TPI_ERROR_U_USE_LIBRARY;
	}

	int nReturnCode = ErrorCodeConvert(((int (PASCAL *)(const char *, long, unsigned int, HLOCAL *)) fpProc)(_szArcName.ToUTF8(), 0, 0, _hArchive));
	if (nReturnCode != TPI_ERROR_SUCCESS)
	{
		return nReturnCode;
	}
	if (_nFileCount != NULL)
	{
		* _nFileCount = ::LocalSize(* _hArchive) / sizeof(fileInfo);
	}
	return * _hArchive == NULL ? TPI_ERROR_IO_ARC_OPEN : nReturnCode;
}

int __stdcall CloseArchive
(
	void * _hArchive
)
{
	return ::LocalFree(_hArchive) == NULL ? TPI_ERROR_SUCCESS : TPI_ERROR_IO_ARC_CLOSE;
}

int __stdcall GetFileInformation
(
	void * _hArchive,
	TPI_FILEINFO * _fiInfo,
	bool _bFirst
)
{
	static wxULongLong_t nFileCount, nFilePointer;

	if (_bFirst)
	{
		nFilePointer = 0;
		nFileCount = ::LocalSize(_hArchive) / sizeof(fileInfo);
	}

	if (nFilePointer > nFileCount)
	{
		return TPI_ERROR_S_ENDOFDATA;
	}

	fileInfo pfiInfo = ((fileInfo *) ::LocalLock(_hArchive))[nFilePointer];
	if (pfiInfo.method[0] == 0)
	{
		// 丁寧なプラグインのための数合わせ (^^;
		nFileCount = nFilePointer;
		return TPI_ERROR_S_ENDOFDATA;
	}

	_fiInfo->dwAttribute    = 0;
	_fiInfo->dwCRC32        = pfiInfo.crc;
	_fiInfo->nPackedSize    = pfiInfo.compsize;
	_fiInfo->nUnpackedSize  = pfiInfo.filesize;
	_fiInfo->wCompressRatio = pfiInfo.compsize >= pfiInfo.filesize ? 1000 : (WORD) (1000 * pfiInfo.compsize / pfiInfo.filesize);
	_fiInfo->nFileId        = nFilePointer++;
	_fiInfo->tmModified     = pfiInfo.timestamp;
	_fiInfo->szStoredName   = MB2String(pfiInfo.path) + MB2String(pfiInfo.filename);
	_fiInfo->fnFileName     = wxFileName(_fiInfo->szStoredName);
	_fiInfo->szMethod       = MB2String((char *) pfiInfo.method);
	_fiInfo->pCustomInfo    = (void *) pfiInfo.position;
	::LocalUnlock(_hArchive);

	return TPI_ERROR_SUCCESS;
}

int __stdcall GetArchiveInformation
(
	void *,
	TPI_ARCHIVEINFO * _aiInfo
)
{
	// GetPluginInfoを実行。
	FARPROC	fpProc = ::GetProcAddress(g_hLib, "GetPluginInfo");
	if (fpProc != NULL)
	{
		char szTemp[20];
		if (((int (PASCAL *)(int, char *, int)) fpProc)(2, szTemp, sizeof(szTemp)) > 0)
		{
			_aiInfo->fiInfo.szSuffix = MB2String(szTemp);
		}
		if (((int (PASCAL *)(int, char *, int)) fpProc)(3, szTemp, sizeof(szTemp)) > 0)
		{
			_aiInfo->fiInfo.szTypeName = MB2String(szTemp);
		}
	}
	_aiInfo->fiInfo.szTPIName = wxT("spiLibrary");
	_aiInfo->fiInfo.eSupportedCommand = TPI_COMMAND_EXTRACT;

	return TPI_ERROR_SUCCESS;
}

int __stdcall Command
(
	wxULongLong_t _eCommand,
	TPI_SWITCHES * _swInfo,
	const wxString & _szArcName,
	const wxArrayString & _szFiles
)
{
	if (_eCommand != TPI_COMMAND_EXTRACT)
	{
		return TPI_ERROR_D_UNSUPPORTED;
	}

	// 展開処理のみを行う。
	FARPROC fpProc = ::GetProcAddress(g_hLib, "GetFile");
	if (fpProc == NULL)
	{
		return TPI_ERROR_U_USE_LIBRARY;
	}

	// 書庫ハンドルを取得。
	void * hArchive;
	int nErrorCode = OpenArchive(_szArcName, & hArchive);
	if (nErrorCode != TPI_ERROR_SUCCESS)
	{
		return nErrorCode;
	}

	// コールバックを送信。
	wxFileName _fnArcName(_szArcName);
	TPI_PROCESSINFO piInfo;
	piInfo.eMessage = TPI_MESSAGE_STATUS;
	piInfo.eStatus  = TPI_STATUS_OPENARCHIVE;
	piInfo.fiInfo.fnFileName = _fnArcName;
	if (CallbackProc(0, 0, (long) & piInfo))
	{
		return TPI_ERROR_D_SKIPPED;
	}

	// 処理実行。
	piInfo.eStatus = TPI_STATUS_INPROCESS;
	nErrorCode = GetFileInformation(hArchive, & piInfo.fiInfo, true);
	if (nErrorCode == TPI_ERROR_SUCCESS)
	{
		do
		{
			// 処理対象かどうか判定。
			if ((! _szFiles.IsEmpty()) && _szFiles.Index(piInfo.fiInfo.szStoredName) == wxNOT_FOUND)
			{
				continue;
			}

			// 処理を行うか確認。
			piInfo.eMessage = TPI_MESSAGE_ASK;
			piInfo.eStatus = TPI_PARAM_DEST;
			piInfo.fnDestination = wxFileName(_swInfo->fnDestinationDirectory.GetPathWithSep() + (_swInfo->fStoreDirectoryPathes ? piInfo.fiInfo.fnFileName.GetFullPath() : piInfo.fiInfo.fnFileName.GetFullName()));
			if (CallbackProc(0, 0, (long) & piInfo))
			{
				nErrorCode = TPI_ERROR_D_SKIPPED;
				break;
			}
			if (! piInfo.fnDestination.IsOk())
			{
				continue;
			}

			// 出力先作成。
			if (! piInfo.fnDestination.Mkdir(0777, wxPATH_MKDIR_FULL))
			{
				nErrorCode = TPI_ERROR_IO_DIR_WRITE;
				break;
			}

			// コールバックを送信。
			piInfo.eMessage = TPI_MESSAGE_STATUS;
			piInfo.eStatus = TPI_STATUS_BEGINPROCESS;
			if (CallbackProc(0, 0, (long) & piInfo))
			{
				nErrorCode = TPI_ERROR_D_SKIPPED;
				break;
			}
			piInfo.eStatus = TPI_STATUS_INPROCESS;

			// ファイル出力には対応してないのでメモリ出力で代行。
			HLOCAL hMemory = NULL;
			nErrorCode = ErrorCodeConvert(((int (PASCAL *)(const char *, long, char *, unsigned int, FARPROC, long)) fpProc)(_szArcName.ToUTF8(), (long) piInfo.fiInfo.pCustomInfo, (char *) & hMemory, 0x0100, (FARPROC) CallbackProc, (long) & piInfo));
			if (nErrorCode == TPI_ERROR_SUCCESS && hMemory == NULL)
			{
				nErrorCode = TPI_ERROR_UNDEFINED;
			}
			if (nErrorCode != TPI_ERROR_SUCCESS)
			{
				break;
			}

			// 展開先に出力。
			wxFile hFile;
			if (! hFile.Create(piInfo.fnDestination.GetFullPath()))
			{
				nErrorCode = TPI_ERROR_IO_FILE_OPEN;
				break;
			}

			bool bErrorOccured = hFile.Write(::LocalLock(hMemory), piInfo.fiInfo.nUnpackedSize) != piInfo.fiInfo.nUnpackedSize;
			::LocalUnlock(hMemory);
			::LocalFree(hMemory);
			hFile.Close();
			if (bErrorOccured)
			{
				nErrorCode = TPI_ERROR_IO_FILE_WRITE;
				break;
			}
			nErrorCode = TPI_ERROR_SUCCESS;

			// コールバックを送信。
			piInfo.eStatus = TPI_STATUS_ENDPROCESS;
			if (CallbackProc(0, 0, (long) & piInfo))
			{
				nErrorCode = TPI_ERROR_D_SKIPPED;
				break;
			}
		}
		while ((nErrorCode = GetFileInformation(hArchive, & piInfo.fiInfo, false)) != TPI_ERROR_S_ENDOFDATA);
		if (nErrorCode == TPI_ERROR_S_ENDOFDATA)
		{
			// 終端に達した場合。
			nErrorCode = TPI_ERROR_SUCCESS;
		}
	}
	CloseArchive(hArchive);

	return nErrorCode;
}

int __stdcall SetCallbackProc
(
	TPI_PROC _prArcProc
)
{
	// ポインタを保存。
	if (_prArcProc == NULL)
	{
		return TPI_ERROR_D_PARAMETER;
	}
	g_prProc = * _prArcProc;

	return TPI_ERROR_SUCCESS;
}

#ifdef __cplusplus
}
#endif
