/*=========================================================================
* 
* edit_ot.cpp :  ObjectTable Editor Object - inplementation
* 
* Version			2.0
* Creation date		07/06/97	Author : Vincent Lhullier	
* Revision date		18/08/97	Author : Shaitan	
*
* Shaitan
*=======================================================================*/

#define HieFriend
#define D_ObjsTbls_Define
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#include <direct.h>

#include "stdafx.h"
#include "acp_base.h"

#include "TFA.h"
#include "x:\cpa\main\inc\_EditID.h"

#include "incGAM.h"
#include "ITF.h"

#include "OT_inter.hpp"
#include "OT_dLoad.hpp"
#include "DPT.h"
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#undef HieFriend

#undef D_ObjsTbls_Define

// infos
static CString g_csTOTName = C_szDLLObjectTableName;
static CString g_csTOTAuthor = "Vincent Lhullier & Chantal Oury";
static CString g_csTOTVersion = "V 2.0.1   18/03/98";
static CString g_csTOTFrenchHelpFile = "";
static CString g_csTOTEnglishHelpFile = "";


/*=============================================================================
		the DLL global definition
=============================================================================*/
tdstDLLIdentity g_stOTIdentity;


/*=============================================================================
		defines
=============================================================================*/
#define C_uiPopupLoad 10


//#################################################################################
// Constructor / Destructor
//#################################################################################

/*===========================================================================
*		Description:	Constructor
*		Creation date:	07/06/97
*		Author:			Vincent Lhullier
*---------------------------------------------------------------------------
*		Revision date:					Author:         
*=========================================================================*/
ObjectTableInterface::ObjectTableInterface(void)
{
	m_p_stDLLIdentity = &g_stOTIdentity;
	
    // Does your DLL can output in main game view ?
	m_stBaseDLLDefinition.bCanOutputIn3DView = FALSE;

	SetCurrent(FALSE); 
    SetEditorInfo(g_csTOTName, g_csTOTAuthor, g_csTOTVersion, g_csTOTFrenchHelpFile, g_csTOTEnglishHelpFile);
}

/*===========================================================================
*		Description:	Destructor
*		Creation date:	07/06/97
*		Author:			Vincent Lhullier
*---------------------------------------------------------------------------
*		Revision date:					Author:         
*=========================================================================*/
ObjectTableInterface::~ObjectTableInterface (void)
{

}

//#################################################################################
// Inits
//#################################################################################

/*===========================================================================
*		Description:	Inits for Scripts
*		Creation date:	07/06/97
*		Author:			Vincent Lhullier
*---------------------------------------------------------------------------
*		Revision date:					Author:         
*=========================================================================*/
void ObjectTableInterface::fn_vJustAfterRegistered()
{
	CString a_csType[] = { C_szObjectTableTypeName };
	fn_vRegisterObjectsType ( a_csType , 1 ) ;
	EditorObjectTable::StaticInit();

	m_lNbUnloaded = 0;
}

/*===========================================================================
*		Description:	Construct
*		Creation date:	18/08/97
*		Author:			Shaitan
*---------------------------------------------------------------------------
*		Revision date:					Author:         
*=========================================================================*/
void ObjectTableInterface::fn_vConstruct(void)
{
	// resources
	HINSTANCE hOldInst = AfxGetResourceHandle();
    AfxSetResourceHandle(m_p_stDLLIdentity->hModule);

    // dialog for load
	m_pDialogLoad = new OT_DialogLoad(this);

	// resources
	AfxSetResourceHandle(hOldInst);
}


//#################################################################################
// Loads
//#################################################################################

/*===========================================================================
*		Description:	Load all object table of a family
*		Creation date:	07/06/97
*		Author:			Vincent Lhullier
*---------------------------------------------------------------------------
*		Revision date:	18/08/97		Author: Shaitan       
*=========================================================================*/
void ObjectTableInterface::m_fn_vLoadFamilyObjectTables( CPA_Family *p_oFamily )
{
	tdxHandleToObjectsTablesList	hOTL;
	SCR_tdst_Link_Value				*p_stLinkValue;
	EditorObjectTable				*p_oOT;
	WIN32_FIND_DATA					stFindData;
	HANDLE							hFind;
	char							szPath[ MAX_PATH];
	char							szFileName[SCR_CV_ui_Cfg_MaxLenName];


	// construct research path
	sprintf(szPath, "%s\\%s\\*.tbl", fn_szGetFamiliesDataPath(), (char *) (LPCTSTR) p_oFamily->GetName() );

	// construct one Editor Object Table for each found files
	hFind = FindFirstFile( szPath, &stFindData );
	if (hFind != INVALID_HANDLE_VALUE)
	{

		*strrchr( szPath, '*' ) = 0;

		do
		{
			sprintf(szFileName, "%s%s", szPath, stFindData.cFileName );
			p_stLinkValue = SCR_fnp_st_Link_SearchKey( &TBL_g_stLinkTable, szFileName );

			if (p_stLinkValue != NULL)
				hOTL = (tdxHandleToObjectsTablesList) SCR_M_ul_Link_GetValue( p_stLinkValue );
			else
				hOTL = NULL;

			// referenced section name = short name 
			sprintf(szFileName, "%s\\%s", (char *) (LPCTSTR) p_oFamily->GetName(), stFindData.cFileName );
			// build editor object
			p_oOT = new EditorObjectTable( this, hOTL, p_oFamily, szFileName );
			// only loaded objects are available for other editors
			p_oFamily->mfn_vAddObjectTable( p_oOT );
			if (!hOTL)
				m_lNbUnloaded++;

		} while (FindNextFile( hFind, &stFindData ));

		// close FindData handle
		FindClose(hFind);
	}

// Shaitan Correction Anims Specifiques
	char szVersion[255];
	char szSearchPath[255];
	char szRealName[255];
	FILE *hIni;

	// get info from ini file
	hIni = fopen("version.ini", "rt");
	if(hIni == NULL)
		hIni = fopen("x:\\cpa\\exe\\main\\version.ini", "rt");
	if(hIni)
	{
		fgets(szVersion, 49, hIni);
		while(!isalnum(szVersion[strlen(szVersion) - 1]))
			szVersion[strlen(szVersion) - 1] = '\0';
		fclose(hIni);
	}
	// if no specific version, no more search
	else
		return;

	char szVersion1[255];
	char szVersion2[255];
	char *szCut;
	int	 iNumVersion, iNbVersions = 1;

	strcpy(szVersion1, szVersion);
	szCut = strchr(szVersion1, ',');
	if (szCut)
	{
		strcpy(szVersion2, szCut+1 );
		strcpy(szCut, "\0");
		iNbVersions = 2;
	}

	for (iNumVersion = 0; iNumVersion < iNbVersions; iNumVersion++)
	{
		// build specific path
		strcpy(szSearchPath, iNumVersion ? szVersion2 : szVersion1);
		strcat(szSearchPath, strchr(fn_szGetFamiliesDataPath(), '\\'));
		
		// construct research path
		sprintf(szPath, "%s\\%s\\*.tbl", szSearchPath, (char *) (LPCTSTR) p_oFamily->GetName() );

		// construct one Editor Object Table for each found files
		hFind = FindFirstFile( szPath, &stFindData );
		if (hFind != INVALID_HANDLE_VALUE)
		{

			*strrchr( szPath, '*' ) = 0;

			do
			{
				BOOL bAlreadyExist;
				
				sprintf(szFileName, "%s%s", szPath, stFindData.cFileName );
				// check if this object table was already loaded in another specific directory
				if (iNumVersion > 0)
				{
					WIN32_FIND_DATA		stPreviousFindData;
					char				szPreviousFile[SCR_CV_ui_Cfg_MaxLenName];

					// build file name for previous version
					strcpy(szPreviousFile, szVersion1);
					strcat(szPreviousFile, strstr(szFileName, "\\"));

					// check if file was already loaded
					bAlreadyExist = (FindFirstFile(szPreviousFile, &stPreviousFindData) != INVALID_HANDLE_VALUE);
					//SCR_fn_c_RdL0_IsSectionExists(szPreviousFile);

				}
				else
					bAlreadyExist = FALSE;

				if (!bAlreadyExist)
				{
					// get engine object
					strcpy(szRealName, fn_szGetFamiliesDataPath());
					strcat(szRealName, szFileName + strlen(szSearchPath));
					p_stLinkValue = SCR_fnp_st_Link_SearchKey( &TBL_g_stLinkTable, szRealName );

					if (p_stLinkValue != NULL)
						hOTL = (tdxHandleToObjectsTablesList) SCR_M_ul_Link_GetValue( p_stLinkValue );
					else
						hOTL = NULL;

					// referenced section name = short name 
					sprintf(szFileName, "%s\\%s", (char *) (LPCTSTR) p_oFamily->GetName(), stFindData.cFileName );
					// build editor object
					p_oOT = new EditorObjectTable( this, hOTL, p_oFamily, szFileName );
					// only loaded objects are available for other editors
					p_oFamily->mfn_vAddObjectTable( p_oOT );
					if (!hOTL)
						m_lNbUnloaded++;
				}

			} while (FindNextFile( hFind, &stFindData ));

			// close FindData handle
			FindClose(hFind);
		}
	}
}


/*===========================================================================
*		Description:	Load engine object associated with editor object
*		Creation date:	07/06/97
*		Author:			Vincent Lhullier
*---------------------------------------------------------------------------
*		Revision date:					Author:		       
*=========================================================================*/
BOOL ObjectTableInterface::fn_bLoadBaseObject(CPA_BaseObject *p_oObject)
{
	((EditorObjectTable *) p_oObject)->fn_vLoadEngineObjectTable();
	return TRUE;
}


//#################################################################################
// Tool DLL functions Overload
//#################################################################################

/*===========================================================================
*		Description:	OnQueryAction => load one LipSync
*		Creation date:	07/06/97
*		Author:			Vincent Lhullier
*---------------------------------------------------------------------------
*		Revision date:					Author:		       
*=========================================================================*/
long ObjectTableInterface::OnQueryAction(CPA_EditorBase *p_oSender, WPARAM _wParam, LPARAM _lParam)
{
//	EditorObjectTable	*p_oOT;
	long				lResult = 0;

	switch (_wParam)
	{
/*
		case C_uiCreateObjectTable:
			tdxHandleToObjectsTablesList	hOTL;
			char							*p_szSectionName;
			char							szFileName[SCR_CV_ui_Cfg_MaxLenName];
			char							szActionName[SCR_CV_ui_Cfg_MaxLenName];
			char							szName[SCR_CV_ui_Cfg_MaxLenName];

			hOTL = (tdxHandleToObjectsTablesList) _lParam;

			p_szSectionName = SCR_M_p_sz_Link_GetKey(SCR_fnp_st_Link_SearchValue(&TBL_g_stLinkTable, (unsigned long) hOTL));
			SCR_fn_v_RdL0_SplitSectionName(p_szSectionName, szFileName, szActionName, szName);
			if (p_szSectionName == NULL)
				p_oOT = new EditorObjectTable( this, GetMainWorld(), hOTL);
			else
			{
				SCR_fn_v_RdL0_SplitSectionName(p_szSectionName, szFileName, szActionName, szName);
				p_oOT = new EditorObjectTable( this, GetMainWorld(), hOTL, szName, szFileName, szActionName);
			}
			lResult = (long) p_oOT;
			break;

		case C_uiDeleteObjectTable:
			p_oOT = (EditorObjectTable *) _lParam;
			delete p_oOT;
			break;
*/
		case C_uiLoadFamilyObjectTables:
			m_fn_vLoadFamilyObjectTables ((CPA_Family *) _lParam);
			break;
	}
	return lResult;
}


/*===========================================================================
*		Description:	Tools Menu => add entry for load
*		Creation date:	18/08/97
*		Author:			Shaitan
*---------------------------------------------------------------------------
*		Revision date:					Author:		       
*=========================================================================*/
BOOL ObjectTableInterface::fn_bDefineSubMenu (EDT_SubMenu *p_oEDTSubMenu)
{
//ANNECY Shaitan NewInterface 24/03/98 {
    if (p_oEDTSubMenu->GetSubMenuType() == C_SubMenuLoad)
//ENDANNECY Shaitan NewInterface }
    {
        p_oEDTSubMenu->AddAnEntry(this, "Load Objects Tables", C_uiPopupLoad, FALSE, m_lNbUnloaded > 0);
        return TRUE;
    }
    return FALSE;
}

/*===========================================================================
*		Description:	Tools Menu => answer to load command
*		Creation date:	18/08/97
*		Author:			Shaitan
*---------------------------------------------------------------------------
*		Revision date:					Author:		       
*=========================================================================*/
void ObjectTableInterface::_OnSubMenuCommand (EDT_SubMenu *p_oEDTSubMenu, UINT uiMsgID)
{
	CPA_List<CPA_BaseObject> *pObjectList;
	CPA_BaseObject			 *pObject;
	POSITION				 pos;
	CString					 csText;
	BOOL					 bRes;
	long					 lNbLoaded = 0;

//ANNECY Shaitan NewInterface 24/03/98 {
	if (p_oEDTSubMenu->GetSubMenuType() == C_SubMenuLoad) 
//ENDANNECY Shaitan NewInterface }
    {
        switch (uiMsgID)
		{
			case C_uiPopupLoad:
				if (m_pDialogLoad->DoModal() == IDOK)
				{
					// get actor editor
					CPA_DLLBase *p_oActorDLL = GetMainWorld() -> GetObjectDLLWithName( C_szDLLActorName );
					// get list of objects to load
					pObjectList = m_pDialogLoad->GetObjectsToLoad();
					// load each object
					for (pObject = pObjectList->GetHeadElement(pos); pObject;
						 pObject = pObjectList->GetNextElement(pos))
					{
						bRes = fn_bLoadBaseObject(pObject);
						if (bRes)
						{
							lNbLoaded++;
							// tell actor DLL that Object Tables were loaded
							if (p_oActorDLL)
								p_oActorDLL -> OnQueryAction( this, C_uiActor_ObjectsTableLoaded, (LPARAM)pObject );
						}
					}
					m_lNbUnloaded -= lNbLoaded;
					if (lNbLoaded)
					{
						csText.Format("%ld Object Tables loaded", lNbLoaded);
						M_GetMainWnd()->UpdateStatus((char*)(LPCSTR)csText, C_STATUSPANE_INFOS, C_STATUS_NORMAL);
					}
				}
				break;
		}		
	}
}
