


#include "lib_prefs.h"
#include "c4d_string.h"
#include "c4d_gui.h"

#ifdef __API_INTERN__
#include "ge_event.h"
#else
#include "c4d_general.h"
#endif


PrefsLib *lib_prefs = NULL;


static PrefsLib *CheckPrefsLib(LONG offset)
{
	return (PrefsLib*)CheckLib(LIBRARY_PREFS,offset,(C4DLibrary**)&lib_prefs);
}


Bool PrefsLib_Register(LONG id,const String &name,PrefsDialogHook *dlg,LONG parentid, LONG sortid)
{
	PrefsLib *lib = CheckPrefsLib(LIBOFFSET(PrefsLib,PrefsLib_Register));
	if (!lib || !lib->PrefsLib_Register) return FALSE;
	return (*lib->PrefsLib_Register)(id,&name,dlg,parentid,sortid);
}



CDialog *iSubDialog_Alloc(PrefsDialogHook *thi,void *&userdata)
{
	if (!thi) return NULL;
	userdata = NULL;
	SubDialog *sub = ((PrefsDialogHookClass*)(thi->thisptr))->Alloc();
	if (!sub) return NULL;
	userdata = sub;
	return sub->Get();
}

void iSubDialog_Free(PrefsDialogHook *thi,void *userdata)
{
	if (!thi) return;
	((PrefsDialogHookClass*)thi->thisptr)->Free((SubDialog*)userdata);
}

void iSubDialog_EditStart(PrefsDialogHook *thi,void *userdata,BaseContainer *bc)
{
	if (!thi) return;
	((PrefsDialogHookClass*)thi->thisptr)->EditStart((SubDialog*)userdata,bc);
}

void iSubDialog_EditApply(PrefsDialogHook *thi,void *userdata,const BaseContainer &originaldata)
{
	if (!thi) return;
	((PrefsDialogHookClass*)thi->thisptr)->EditApply((SubDialog*)userdata,originaldata);
}

void iSubDialog_EditUndo(PrefsDialogHook *thi,void *userdata,const BaseContainer &originaldata)
{
	if (!thi) return;
	((PrefsDialogHookClass*)thi->thisptr)->EditUndo((SubDialog*)userdata,originaldata);
}




PrefsDialogHookClass::PrefsDialogHookClass()
{
	hook.thisptr = this;
	hook.SubDialog_Alloc      = iSubDialog_Alloc    ;
	hook.SubDialog_Free       = iSubDialog_Free     ;
	hook.SubDialog_EditStart  = iSubDialog_EditStart;
	hook.SubDialog_EditApply	= iSubDialog_EditApply;
	hook.SubDialog_EditUndo		= iSubDialog_EditUndo	;
}

Bool PrefsDialogHookClass::Register(LONG id,const String &name,LONG parentid, LONG sortid)
{
	return PrefsLib_Register(id,name,&hook,parentid,sortid);
}

SubDialog *PrefsDialogHookClass::Alloc() 
{ 
	return NULL;
}

void PrefsDialogHookClass::Free(SubDialog *dlg) 
{
}

void PrefsDialogHookClass::EditStart(SubDialog *dlg,BaseContainer *t_worldedit) 
{
	worldedit = t_worldedit;
}

void PrefsDialogHookClass::EditApply(SubDialog *dlg,const BaseContainer &originaldata) 
{
}

void PrefsDialogHookClass::EditUndo(SubDialog *dlg,const BaseContainer &originaldata) 
{
}

BaseContainer *PrefsDialogHookClass::GetData()
{
	return worldedit;
}



Bool PrefsDlg_Base::Command(LONG id,const BaseContainer &msg)
{
	BaseContainer *data = hook->GetData();
	if (!data) return TRUE;
	LONG res = CommandValues(id,msg,data);
	EnableValues(data);			
	if (res)
	{
		if (!msg.GetLong(BFM_ACTION_STRCHG) && !msg.GetLong(BFM_ACTION_VALCHG) && !msg.GetLong(BFM_ACTION_INDRAG))
		{
			BaseContainer m(0xdeadbeef);
			SendParentMessage(m);
		}
	}

	return SubDialog::Command(id,msg);
}
