// AplAPI.cpp : Implementation of CAplAPI

#include "stdafx.h"
#include "APL_PSS_API.h"
#include "AplAPI.h"
#include "GeneralFunctions.h"
#include <apl_api.h>
#include <AutoUpdate.h>
#include "aplClassifierMgr.h"
#include "aplMapElement.h"

/////////////////////////////////////////////////////////////////////////////
// CAplPssAPI

CAplPssAPI::CAplPssAPI():m_ctlStatic(_T("AplDataControl"), this, 1)
{
	m_bWindowOnly = TRUE;
	
	m_api= NULL;
	if(!m_api)
	{
		m_api= new CaplAPI;
		m_bCanDelete= true;
		m_api->m_data.m_IsWaitDlg=false;
	}
}

CAplPssAPI::~CAplPssAPI()
{
	if(m_api && m_bCanDelete)
	{
		delete m_api;
		m_api= NULL;
	}
}

LRESULT CAplPssAPI::OnSetFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	LRESULT lRes = CComControl<CAplPssAPI>::OnSetFocus(uMsg, wParam, lParam, bHandled);
	if (m_bInPlaceActive)
	{
		DoVerbUIActivate(&m_rcPos,  NULL);
		if(!IsChild(::GetFocus()))
			m_ctlStatic.SetFocus();
	}
	return lRes;
}

LRESULT CAplPssAPI::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	RECT rc;
	GetWindowRect(&rc);
	rc.right -= rc.left;
	rc.bottom -= rc.top;
	rc.top = rc.left = 0;
	m_ctlStatic.Create(m_hWnd, rc);
	return 0;
}

STDMETHODIMP CAplPssAPI::SetObjectRects(LPCRECT prcPos,LPCRECT prcClip)
{
	IOleInPlaceObjectWindowlessImpl<CAplPssAPI>::SetObjectRects(prcPos, prcClip);
	int cx, cy;
	cx = prcPos->right - prcPos->left;
	cy = prcPos->bottom - prcPos->top;
	::SetWindowPos(m_ctlStatic.m_hWnd, NULL, 0, 0, cx, cy, SWP_NOZORDER | SWP_NOACTIVATE);
	return S_OK;
}

// ISupportsErrorInfo
STDMETHODIMP CAplPssAPI::InterfaceSupportsErrorInfo(REFIID riid)
{
	static const IID* arr[] = 
	{
		&IID_IAplAPI,
	};
	for (int i=0; i<sizeof(arr)/sizeof(arr[0]); i++)
	{
		if (InlineIsEqualGUID(*arr[i], riid))
			return S_OK;
	}
	return S_FALSE;
}

STDMETHODIMP CAplPssAPI::Test(BOOL *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	AfxMessageBox(_T("Test"), MB_OK);

	LONG mes_val(8);
//	Fire_SendMes(mes_val);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::Test1(BOOL *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	AfxMessageBox(_T("Test1"), MB_OK);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::InitAPI(long apiInstance, BOOL *result)
{
	
	AFX_MANAGE_STATE(AfxGetStaticModuleState())	
	if(!apiInstance) return S_OK;

	if(m_api && m_bCanDelete)
	{
		if(m_api->m_data.IsConnected())
			m_api->Disconnect();

		delete m_api;
		m_api= NULL;
	}
	
	m_api= (CaplAPI*)apiInstance;
	if(m_api)m_wf_mgr.Attach(m_api);
	m_bCanDelete= false;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetAPI(long *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	*result= (long)m_api;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::Connect(BSTR userName, BSTR passWord, BSTR baseName, 
								   /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
//	CWinApp* theApp=AfxGetApp();
//	HINSTANCE m_hInstOld = AfxGetResourceHandle();
//	AfxSetResourceHandle(theApp->m_hInstance);

	CString sPW(passWord),
		sUser(userName),
		sBase(baseName);
	
	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->Connect(sUser, sPW, sBase);///*sUser-*/_T(""), sPW, sBase);
	
//	AfxSetResourceHandle(m_hInstOld);
	
	if(bRes)
	{
		if(m_api->m_data.m_CurSchema!=_T("apl_tgb_a"))  // Для схемы TGB это не выделяем
		{
			m_wf_mgr.Attach(m_api);

			result->boolVal= (short)0xffff;
			m_api->Init();
			
			CaplLoadData ld(&m_api->m_data,DEF_SOURCE);

			CaplInstance *inst=m_api->m_data.GetCurrUser();
			if(inst!=0)
			{
				CaplAttr* attr=m_api->m_data.GetAttrDefinitionBN(_T("apl_user"),_T("personality"));
				ld.AddQuery(_T('i'), inst->GetId(), 0,attr, true);
				ld.LoadEx();
				ld.ClearQuery();
			}
		}

//		m_api->m_data.SetAutoDownloadMode(true);
	}
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::ConnectNoDlg(BSTR userName, BSTR password, BSTR connect, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString sPW(password),
		sUser(userName),
		sBase(connect);
	
	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->Connect(sUser, sPW, sBase, 0, _T(""), true);///*sUser-*/_T(""), sPW, sBase);
	if(bRes)
	{
		m_wf_mgr.Attach(m_api);

		result->boolVal= (short)0xffff;
		m_api->Init();
		
		CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
		
		CaplInstance *inst=m_api->m_data.GetCurrUser();
		if(inst!=0)
		{
			CaplAttr* attr=m_api->m_data.GetAttrDefinitionBN(_T("apl_user"),_T("personality"));
			ld.AddQuery(_T('i'), inst->GetId(), 0,attr, true);
			ld.LoadEx();
			ld.ClearQuery();
		}
	}
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::Disconnect(/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL;
	result->boolVal= (short)0xffff;
	
	bool bRes= true;

	if(m_api->m_data.IsConnected())
	{
		bRes= m_api->Disconnect();
		m_wf_mgr.Detach();
	}

	if(!bRes) result->boolVal= 0;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::ReplaceInstance(long instance1, long instance2, BOOL bSelectInstances, BOOL bAutoRun, BOOL bAutoHide, VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	if(aplReplaceInstance(&(m_api->m_data), (CaplInstance*) instance1, (CaplInstance*)instance2, 
		(bSelectInstances==TRUE)?true:false, (bAutoRun==TRUE)?true:false, (bAutoHide==TRUE)?true:false))
		result->boolVal=(short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::UpdatePSS(VARIANT* NeedExitApp)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	NeedExitApp->vt=VT_BOOL;
	NeedExitApp->boolVal= 0;

	CaplAutoUpdate au(_T("PSS"));
	au.LoadOptions();
	if(au.m_AutoUpdate)
	{
		au.m_data=&(m_api->m_data);  // Та, что в внутри компонента
		if(au.Update(true,false)) 
			NeedExitApp->boolVal= (short)0xffff;
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetOraAlias(VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt= VT_BSTR;
	
	if(!m_api || !m_api->m_data.IsConnected())
		return S_OK;
	
	CString sAlias;
	CString sUser;
	CString sPassword;
	if(m_api->m_data.NET_GetOraAlias(100, 100^0x7d24cf18, sAlias, sUser, sPassword))
	{
#ifdef _UNICODE
		result->bstrVal= W2BSTR(LPCWSTR(sAlias));
#else
		result->bstrVal= A2BSTR(LPCSTR(sAlias));
#endif
	}
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::SaveChanges(/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api->m_data.IsConnected()) return S_OK;
	
	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	bool bRes= m_api->m_data.NET_SaveChanges();
	
	if(bRes)
		result->boolVal= (short)0xffff;
	
	return S_OK;
}
STDMETHODIMP CAplPssAPI::GetAttr(long instance, long attr, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	if(result==0) return S_OK;
	
	COleVariant oleValue;
	CaplValue *value;	

	bool bAssert= m_api->m_data.GetAttr((CaplInstance*) instance, (CaplAttr*)attr, &value);
	//Проверка типа возвращенного значения 
	//и упаковка его в структуру VARIANT:
	if(value!=0)
	{
		switch (value->type)
		{
			case aplINTEGER: oleValue = (long)(value->ival); break;
			case aplREAL: oleValue= (double)(value->rval); break;
			case aplBOOL: 
				{
					oleValue.vt= VT_BOOL;
					oleValue.boolVal= 0;
					if(value->bval) oleValue.boolVal= (short)0xffff;
//					oleValue= (long)(value->bval);break;
				}
			case aplLOGICAL: oleValue= (long)(value->lval); break;
			case aplINSTANCE: oleValue = (long)(value->instval); break;
			case aplSTRING: oleValue= (char*)(value->sval); break;
			case aplAGGR: 
				{
					if(value->aggrval->type==aplSTRING)
					{
						BSTRArray tempArray;
						
						for(int i= 0; i<value->aggrval->GetSize(); i++)
						{
							CString str;
							value->aggrval->GetByIndex(i, str);
#ifdef _UNICODE
							tempArray.Add(W2BSTR(LPCWSTR(str)));
#else
							tempArray.Add(A2BSTR(LPCSTR(str)));
#endif
						}

						FillVariant<BSTRArray, BSTR>((LPVARIANT)oleValue, tempArray, VT_BSTR);
					}
					else if(value->aggrval->type==aplINSTANCE)
					{
						LongArray tempArray;
						CaplInstance* inst;

						for(int i= 0; i<value->aggrval->GetSize(); i++)
						{
							inst= NULL;
							value->aggrval->GetByIndex(i, inst);
							if(inst) tempArray.Add((long)inst);
						}

						FillVariant<LongArray, long>((LPVARIANT)oleValue, tempArray, VT_I4);
					}
				}
				break;
		}
	}
	*result= oleValue.Detach();		

	return S_OK;	
}

STDMETHODIMP CAplPssAPI::GetAttrBN(long instance, BSTR attrName, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	CString sName(attrName);
	CaplAttr* attr= m_api->m_data.GetAttrDefinition(((CaplInstance*)instance)->GetType(), sName);
	GetAttr(instance, (long)attr, result);

	return S_OK;
}

bool aplVariant2aplValue (VARIANT &Value, CaplValue &tempValue)
{
	tempValue.Clear();

	VARIANT varValue,varValue1;
	VariantInit(&varValue);
	VariantInit(&varValue1);
	varValue= Value;

	while (varValue.vt==(VT_VARIANT|VT_BYREF))
	{
		varValue1= *(varValue.pvarVal);
		varValue=varValue1;
	}

	switch(varValue.vt)
	{
		case VT_I2: ///*int*/
			tempValue.ival = varValue.iVal;
			tempValue.type= aplINTEGER;
			break;
		case VT_UI2: ///*int*/
			tempValue.ival = varValue.uiVal;
			tempValue.type= aplINTEGER;
			break;
		case VT_R4: /*float*/
			tempValue.rval= varValue.fltVal;
			tempValue.type= aplREAL;
			break;
		case VT_R8: /*double*/
			tempValue.rval= varValue.dblVal;
			tempValue.type= aplREAL;
			break;
		case VT_BOOL: /*bool*/ 
			if(varValue.boolVal) tempValue.bval= true;
			else tempValue.bval= false;
			tempValue.type= aplBOOL;
			break;
		case VT_UI1: /*char*/
			tempValue.lval= varValue.bVal;
			tempValue.type= aplLOGICAL;
			break;
		case VT_I4: /*CInstance или int */ 
			tempValue.ival= varValue.lVal;
			tempValue.type= aplINTEGER;
			break;
		case VT_UI4: /*CInstance или int */ 
			tempValue.ival= varValue.ulVal;
			tempValue.type= aplINTEGER;
			break;
		case VT_INT: /*CInstance или int */ 
			tempValue.ival= varValue.intVal;
			tempValue.type= aplINTEGER;
			break;
		case VT_UINT: /*CInstance или int */ 
			tempValue.ival= varValue.uintVal;
			tempValue.type= aplINTEGER;
			break;
		case VT_BSTR: /*char**/
			{
				CString sStr=varValue.bstrVal;
				tempValue.Set(sStr);
				tempValue.type= aplSTRING;
			}
			break;
		case VT_ARRAY|VT_I4: /* Считаем что массивов int у нас нет*/
			{			
				LongArray tempArray;
				GetVariant<LongArray, long>(varValue, tempArray);
				
				aplExtent ext;
				for(int i=0; i<tempArray.GetSize(); ++i)
					ext.Add((CaplInstance*)tempArray[i]);

				tempValue.Set(ext);
			}
			break;
		case VT_ARRAY|VT_BSTR:
			{
				BSTRArray tempArray;
				GetVariant<BSTRArray, BSTR>(varValue, tempArray);

				CaplAggr aggr;
				for(int i= 0; i<tempArray.GetSize(); ++i)
				{
					CString buf(tempArray[i]);
					aggr.Add(buf);
				}
				tempValue.Set(aggr);
			}
			break;
		default: return false; //"Неизвестный" тип данных.
			break;
	}

	return true;
}

STDMETHODIMP CAplPssAPI::PutAttr(long instance, long attr, VARIANT value, VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	if(attr==0) return S_OK;
	
	CaplValue tempValue;

	if(!aplVariant2aplValue(value,tempValue))return S_OK;


	CaplAttr *at= (CaplAttr*)attr;
	if((at->type==aplINSTANCE) ||(at->type==aplSELECT))
	{
		if(tempValue.type==aplINTEGER)
		{
			CaplInstance *inst=(CaplInstance *)tempValue.ival;
			tempValue.instval= inst;
			tempValue.type= aplINSTANCE;
		}
	}
	else if (at->type==aplREAL)
	{
		if(tempValue.type==aplINTEGER)
		{
			double d =tempValue.ival;
			tempValue.rval= d;
			tempValue.type= aplREAL;
		}
	}

	if(m_api->m_data.PutAttr((CaplInstance*) instance, (CaplAttr*)attr, tempValue))
		result->boolVal= (short)0xffff;
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::PutAttrBN(long instance, BSTR attrName, VARIANT value, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	CString sName(attrName);
	CaplAttr* attr= m_api->m_data.GetAttrDefinition(((CaplInstance*)instance)->GetType(), sName);
	PutAttr(instance, (long)attr, value, result);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateInstance(BSTR entity, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
   //	можно работать с файлом if(!m_api->m_data.IsConnected()) return S_OK;

	CString sEntityName(entity);

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_data.CreateInstanceBN(sEntityName);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteInstance(long instance, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	result->vt=VT_BOOL; 
	result->boolVal= 0;

//	if(!m_api->m_data.IsConnected()) return S_OK;
	
	if(m_api->m_data.DeleteInstance((CaplInstance*)instance))
	{
		result->boolVal= (short)0xffff;	
	}	

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadEntityExtentFromDB(BSTR entity, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api->m_data.IsConnected()) return S_OK;
	
	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	if(!m_api->m_data.IsConnected()) return S_OK;
	
	CString sEntityName(entity);
	if(sEntityName.IsEmpty()) return S_OK;

	CaplEntity* pEntity= NULL;
	pEntity= m_api->m_data.GetEntityBN(sEntityName);
	if(!pEntity) return S_OK;

	CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
	ld.AddQuery(_T('e'), 0, pEntity, 0, true);
	if(ld.LoadEx())
	{
		result->boolVal= (short)0xffff;		
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetEntityExtent(long entity, VARIANT *extent, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())	
	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent ext;
	LongArray array;

	if(m_api->m_data.GetEntityExtent((CaplEntity*)entity, ext))
	{
		for(int i=0; i<ext.GetSize(); ++i)
			array.Add((long)ext[i]);
		FillVariant<LongArray, long>(extent, array, VT_I4);	
		
		result->boolVal= (short)0xffff;	
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetEntityExtentBN(BSTR entity, VARIANT *extent, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())	
	CString sEntityName(entity);
	
	CaplEntity* pEntity= m_api->m_data.GetEntityBN(sEntityName);
	if(pEntity)	GetEntityExtent((long)pEntity, extent, result);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetAttrDefinition(long entity, BSTR attrName, long *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString sName(attrName);
	*result= (long)m_api->m_data.GetAttrDefinition((CaplEntity*) entity, sName);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetEntityDefinition(BSTR entityName, long *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	CString sEntityName(entityName);

	*result= (long) m_api->m_data.GetEntityBN(sEntityName);
	return S_OK;
}


STDMETHODIMP CAplPssAPI::GetEntityName(long entity, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())	
	result->vt= VT_BSTR;
	
	if(entity)
	{
#ifdef _UNICODE
		result->bstrVal= W2BSTR(LPCWSTR(((CaplEntity*)entity)->name));
#else
		result->bstrVal= A2BSTR(LPCSTR(((CaplEntity*)entity)->name));
#endif
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetAttrName(long attr, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt= VT_BSTR;
	
	if(attr)
	{
#ifdef _UNICODE
		result->bstrVal= W2BSTR(LPCWSTR(((CaplAttr*)attr)->name));
#else
		result->bstrVal= A2BSTR(LPCSTR(((CaplAttr*)attr)->name));
#endif
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetInstanceTypeId(long instance, long *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	*result=0;
	if(!instance) return S_OK;

	CaplInstance* pInstance= (CaplInstance*)instance;
	
	*result= (long)(pInstance->GetType());

	return S_OK;
}


STDMETHODIMP CAplPssAPI::GetInstanceType(long instance, 
										   /*BSTR*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	// можно работать с файлом if(!m_api->m_data.IsConnected()) return S_OK;
	if(!instance) return S_OK;
	CaplInstance* pInstance= (CaplInstance*)instance;	
	CString sResult= pInstance->GetType()->name;
	result->vt= VT_BSTR;
#ifdef _UNICODE
	result->bstrVal= W2BSTR(LPCWSTR(sResult));
#else
	result->bstrVal= A2BSTR(LPCSTR(sResult));
#endif
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetInstanceId(long instance, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	// можно работать с файлом if(!m_api->m_data.IsConnected()) return S_OK;
	if(!instance) return S_OK;

	CaplInstance* pInstance= (CaplInstance*)instance;	
	result->vt= VT_I4;	
	result->lVal= pInstance->GetId();

	return S_OK;
}

STDMETHODIMP CAplPssAPI::IsKindOf(long instance, long type, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	if(!instance) return S_OK;
	if(!type) return S_OK;
	bool bRes= m_api->m_data.IsKindOf((CaplInstance*) instance, (CaplEntity*)type);
	if(bRes)
		result->boolVal= (short)0xffff;

	return S_OK;
}


STDMETHODIMP CAplPssAPI::IsKindOfBN(long instance, BSTR type, 
									  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	// можно работать с файлом if(!m_api->m_data.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	CString sType(type);

	if(!instance) return S_OK;

	bool bRes= m_api->m_data.IsKindOfBN((CaplInstance*) instance, sType);
	if(bRes)
		result->boolVal= (short)0xffff;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::IsValidInstance(long instance, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_data.IsMyInstance((CaplInstance*)instance))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SelectInstance(long selectMode, VARIANT rootObjects, BSTR title, 
									  /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString sTitle(title);
	
	aplExtent rootExt;	
	LongArray arrayIn;
	
	GetVariant<LongArray, long>(rootObjects, arrayIn);
	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		rootExt.Add((CaplInstance*)arrayIn[i]);
	}
	
	aplExtent * ext= NULL;
	if(rootExt.GetSize()) ext= &rootExt;
	
	result->vt= VT_I4;
	result->lVal= (long)m_api->m_prd_mgr.SelectInstance(selectMode, sTitle, ext);

//	aplExtent ext1;
//	
//	m_api->m_appr_mgr.SelectPersonOrOrganization(APL_MODE_SELECT_PERSON|APL_MODE_SELECT_OFFICIAL, ext1, _T(""), _T(""));
//	m_api->m_prd_mgr.SelectInstance(APL_MODE_SELECT_PDF, _T(""));
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::QueryExecute(BSTR queryString, BSTR* errorDescription, VARIANT *objArray, BOOL showDlg, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString sQueryString(queryString), sError;
	aplExtent ext;
	LongArray array;
	bool bContinue= true, bShowdlg= true;	
	if(!showDlg) bShowdlg= false;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	if(!m_api->m_data.NET_QueryEditParse(sQueryString, bShowdlg, &sError))
	{
#ifdef _UNICODE
		*errorDescription= W2BSTR(LPCWSTR(sError));
#else
		*errorDescription= A2BSTR(LPCSTR(sError));
#endif
	}
	else
	{
		if(m_api->m_data.NET_QueryExecute(ext, APL_T("Подождите, идет обработка запроса...")))
		{
			for(int i=0; i<ext.GetSize(); ++i)
				array.Add((long)ext[i]);
			FillVariant<LongArray, long>(objArray, array, VT_I4);		

			result->boolVal= (short)0xffff;		
		}
		else MessageBox(APL_T("Ошибка при выполнении запроса."), APL_T("Ошибка"), MB_ICONERROR|MB_OK);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::IsUsedAccessPatterns(VARIANT Instances, VARIANT* UsedPatterns, /*[out,retval]*/ VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	CUIntArray used;

	aplExtent tempInExt;
	LongArray arrayIn, outArray;
	
	GetVariant<LongArray, long>(Instances, arrayIn);
	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		tempInExt.Add((CaplInstance*)arrayIn[i]);
	}

	if(m_api->m_data.NET_IsUsedAccessPatterns(tempInExt, used))
	{
		result->boolVal= (short)0xffff;		
		for(int i=0; i<used.GetSize(); ++i)
			outArray.Add(used[i]);
		FillVariant<LongArray, long>(UsedPatterns, outArray, VT_I4);		
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::IsUsedAccessPattern(/*[in]*/ long instance, /*[out,retval]*/ VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	if(m_api->m_data.NET_IsUsedAccessPattern((CaplInstance*)instance))
		result->boolVal= (short)0xffff;		

	return S_OK;
}

STDMETHODIMP CAplPssAPI::PrepareAccessStringPattern(/*[in]*/ BSTR sPatern, /*[in, defaultvalue(_T(""))]*/ BSTR* sDefinition, /*[out,retval]*/ VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	CString sPatternStr(sPatern);
	CString sDefinitionStr;

	if(m_api->m_data.PrepareAccessStringPattern(sPatternStr, &sDefinitionStr))
	{
		result->boolVal= (short)0xffff;
#ifdef _UNICODE
		*sDefinition= W2BSTR(LPCWSTR(sDefinitionStr));
#else
		*sDefinition= A2BSTR(LPCSTR(sDefinitionStr));
#endif
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::RefreshAccessPatterns(/*[out,retval]*/ VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_data.NET_RefreshAccessPatterns())
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SetAccessFromPatternInst(/*[in]*/ VARIANT Instances, /*[in]*/ long Pattern, /*[out,retval]*/ VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent tempInExt;
	LongArray arrayIn;

	CaplInstance* pattern_inst= (CaplInstance*)Pattern;
	if(!m_api->m_data.IsMyInstance(pattern_inst, true))
		return S_OK;

	GetVariant<LongArray, long>(Instances, arrayIn);
	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		tempInExt.Add((CaplInstance*)arrayIn[i]);
	}

	if(m_api->m_data.NET_SetAccessFromPatternInst(&tempInExt, pattern_inst))
		result->boolVal= (short)0xffff;

	return S_OK;
}


STDMETHODIMP CAplPssAPI::GetInstanceAccessMode2Users(/*[in]*/ long instance, /*[in]*/ VARIANT users, /*[out]*/ VARIANT* usersAccess, /*[out,retval]*/ VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent tempInExt;
	LongArray arrayIn;
	LongArray arrayOut;
	
	aplListAccess2Inst ListAccess;
	aplAccess2Inst* inst_access; 
	aplExtent ext_group;
	CaplInstance *group;
	int i,j,indx;
	CString str_pattern;

	aplUsers access_table;
	aplAccessList *list;

	CaplInstance *ciUser (NULL);
	CaplInstance *ciInstance= (CaplInstance*)instance;
	CaplInstance *pattern, *user;

	CaplMap map_access_ind,map_access_pat;
	map_access_ind.bAutoSort=true;
	map_access_pat.bAutoSort=true;


	aplAccessModeType def_access, def_pat_access, rez_access, tmp_access;

	// изучаемый инстанс
	if(!m_api->m_data.IsMyInstance(ciInstance, true))
		return S_OK;
	
	// формируем структурку для запроса индивидуального доступа
	inst_access=new aplAccess2Inst();
	inst_access->inst=ciInstance;

	// входной список юзеров, для которых ищем доступ. Проверяем, что это именно юзеры
	GetVariant<LongArray, long>(users, arrayIn);
	for(i=0; i<arrayIn.GetSize(); ++i)
	{
		ciUser= (CaplInstance*)arrayIn[i];
		// проверяем что инстанс наш
		if(!m_api->m_data.IsMyInstance(ciUser, true))
			return S_OK;
		// доступ определяем только для пользователей
		if(!m_api->m_data.IsKindOf(ciUser, m_api->m_data.m_ent_apl_user))
			return S_OK;
		inst_access->Add(ciUser,(aplAccessModeType)0);
	}

	ListAccess.Add(inst_access);

	// читаем с сервера доступ к инстансе (для всех юзеров)
	// все юзера с группами и шаблоны - так же грузятся на клиента внутри этой функции
	if(!m_api->m_data.NET_GetGroupeAccessBI(ListAccess,APL_T("Загрузка данных о доступе")))
		return S_OK;

	inst_access = ListAccess.GetAt(0);
	if(inst_access==0)
		return S_OK;

	// готовим данные
	def_access = (aplAccessModeType)inst_access->access_def;
	pattern = inst_access->pattern;

	// для шаблона - если он задан - читаем и парсим строчку, заполняем мапу
	if(pattern!=0)
	{
		// разбираем шаблон
		m_api->m_data.GetAttr(pattern,m_api->m_data.m_attr_apl_acc_pat__pattern,str_pattern);
		m_api->m_data.ParseAccessStringPattern(str_pattern,access_table);
		
		// идем по разобранному шаблону
		for(j=0;j<access_table.GetSize();j++)
		{
			list=access_table.GetAt(j);
			if(list==0) continue;
			if(list->GetSize()>0)
			{
				if(list->user==0)
					def_pat_access = (aplAccessModeType)list->GetAt(0)->access;
				else
					map_access_pat.Add((long)list->user,(long)list->GetAt(0)->access);
			}
		}
	}

	// для индивидуального доступа - если он задан - заполняем мапу
	if(inst_access->is_individual==TRUE)
	{
		aplAccessModeType ch_access;
		for(j=0;j<inst_access->GetSize();j++)
		{
			inst_access->Get(j, &user, ch_access);
			map_access_ind.Add((long)user, (long)ch_access);
		}
	}

	// для каждого юзера из входного массива компонуем окончательный доступ
	for(i=0; i<arrayIn.GetSize(); ++i)
	{
		ciUser= (CaplInstance*)arrayIn[i];
		rez_access = aplNOT_DEFINED;

		// не админ ли?
		if(ciUser->GetId()==DEFAILT_ID_ADMIN_USER)
		{
			// админ!
			rez_access = aplOWN;
		}
		else
		{
			// А может, в группе админов?
			m_api->m_data.GetAttr(ciUser,m_api->m_data.m_attr_apl_user__grop,ext_group);

			for(int i=0;i<ext_group.GetSize();i++)
			{
				if(ext_group.GetAt(i)->GetId()==DEFAILT_ID_ADMIN_GROUP )
				{
					rez_access = aplOWN;
					break;
				}
			}
		}
		// если доступ не определился (не админ) и есть индивидуальный доступ - ищем в нем
		if(rez_access == aplNOT_DEFINED && inst_access->is_individual==TRUE)
		{
			// индивидуальный доступ для этого пользователя есть?
			indx = map_access_ind.QFindByIn((long)ciUser);
			if(indx !=-1)
			{
				rez_access = (aplAccessModeType)map_access_ind[indx].out;
			}
			else
			{
				// а для групп этого пользователя?
				for(j=0;j<ext_group.GetSize();j++)
				{
					group = ext_group.GetAt(j);
					indx = map_access_ind.QFindByIn((long)group);
					if(indx !=-1)
					{
						// из группового доступа ищем самый сильный
						tmp_access = (aplAccessModeType)map_access_ind[indx].out;
						if(rez_access > tmp_access)rez_access = tmp_access;
					}
				}
			}
		}
		// если индивидуальный доступ не задан и есть шаблон - ищем в шаблоне
		if(rez_access == aplNOT_DEFINED && pattern!=0)
		{
			// личный доступ
			indx = map_access_pat.QFindByIn((long)ciUser);
			if(indx !=-1)
			{
				rez_access = (aplAccessModeType)map_access_pat[indx].out;
			}
			else
			{
				// а для групп?
				for(j=0;j<ext_group.GetSize();j++)
				{
					group = ext_group.GetAt(j);
					indx = map_access_pat.QFindByIn((long)group);
					if(indx !=-1)
					{
						// из группового доступа ищем самый сильный
						tmp_access = (aplAccessModeType)map_access_pat[indx].out;
						if(rez_access > tmp_access)rez_access = tmp_access;
					}
				}
			}
			// если шаблон есть, но в нем нет указанного пользователя и его групп - пытаемся взять доступ по умолчанию из шаблона
			if(rez_access == aplNOT_DEFINED)
			{
				rez_access = def_pat_access;
			}
		}
		// Если нет ни индивидуального доступа, ни по шаблону - то берем доступ по умолчанию
		if(rez_access == aplNOT_DEFINED)
		{
			rez_access = def_access;
		}
		arrayOut.Add(rez_access);
	}

	FillVariant<LongArray, long>(usersAccess, arrayOut, VT_I4);
	result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::RemoveAccessAgent(/*[in]*/ VARIANT Instances, /*[in]*/ long access_agent, /*[out,retval]*/ VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent tempInExt;
	LongArray arrayIn;

	CaplInstance* access_agent_inst= (CaplInstance*)access_agent;
	if(!m_api->m_data.IsMyInstance(access_agent_inst, true))
		return S_OK;

	GetVariant<LongArray, long>(Instances, arrayIn);
	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		tempInExt.Add((CaplInstance*)arrayIn[i]);
	}

	if(m_api->m_data.NET_RemoveAccessAgent(tempInExt, access_agent_inst))
		result->boolVal= (short)0xffff;

	return S_OK;
}
STDMETHODIMP CAplPssAPI::SetAccessFromPatternName(/*[in]*/ VARIANT Instances, /*[in]*/ BSTR Pattern, /*[out,retval]*/ VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
		result->vt=VT_BOOL; result->boolVal= 0;

	CString sPatternStr(Pattern);
	
	aplExtent tempInExt;
	LongArray arrayIn;

	GetVariant<LongArray, long>(Instances, arrayIn);
	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		tempInExt.Add((CaplInstance*)arrayIn[i]);
	}

	if(m_api->m_data.NET_SetAccessFromPatternName(&tempInExt, sPatternStr))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SetInstancesAccess2(VARIANT instances, long userOrWG, long accessLevel, long AccessPattern, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	CaplInstance* puserOrWG= (CaplInstance*)userOrWG;
	if(puserOrWG!= (CaplInstance*)-1 && !m_api->m_data.IsMyInstance(puserOrWG))
		return S_OK;
	CaplInstance* pattern= NULL;
	if(AccessPattern!=-1 && AccessPattern!=NULL)
	{
		pattern= (CaplInstance*)AccessPattern;
		if(!m_api->m_data.IsMyInstance(pattern))
			return S_OK;		
	}

	aplAccessModeType mode;
	switch(accessLevel) 
	{
	case 0: mode= aplOWN;
		break;
	case 1: mode= aplRW;
		break;
	case 2: mode= aplRO;
		break;
	case 3: mode= aplNO;
		break;
	default: mode= aplNOT_DEFINED;
		break;
	}

	aplExtent tempInExt;
	LongArray arrayIn;

	GetVariant<LongArray, long>(instances, arrayIn);
	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		tempInExt.Add((CaplInstance*)arrayIn[i]);
	}

	if(m_api->m_data.NET_SetInstancesAccess(&tempInExt, puserOrWG, mode, APL_T("Установка доступа..."), pattern))
		result->boolVal= (short)0xffff;
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::SetInstancesAccess(VARIANT instances, long userOrWG, long accessLevel, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplAccessModeType mode;
	switch(accessLevel) 
	{
		case 0: mode= aplOWN;
			break;
		case 1: mode= aplRW;
			break;
		case 2: mode= aplRO;
			break;
		case 3: mode= aplNO;
			break;
		default: mode= aplNOT_DEFINED;
			break;
	}

	aplExtent tempInExt;
	LongArray arrayIn;
	
	GetVariant<LongArray, long>(instances, arrayIn);
	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		tempInExt.Add((CaplInstance*)arrayIn[i]);
	}
	
	if(m_api->m_data.NET_SetInstancesAccess(&tempInExt, (CaplInstance*)userOrWG, mode, APL_T("Установка доступа...")))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SetAccessByPatternName(VARIANT instances, BSTR sPatternName, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	aplExtent ext;
	CString sPatName(sPatternName), sPattern, buf;
	bool bLoad= false;
	
	sPatName.MakeLower();

	while(sPattern.IsEmpty() && !bLoad)// сначала смотрим по кэшу
	{
		m_api->m_data.GetEntityExtent(m_api->m_appr_mgr.e_apl_acc_pat, ext);
		for(int i= 0; i<ext.GetSize(); i++)
		{
			m_api->m_data.GetAttr(ext[i], m_api->m_appr_mgr.a_apl_acc_pat_name, buf);
			buf.MakeLower();
			if(!sPatName.Compare(buf))
			{
				m_api->m_data.GetAttr(ext[i], m_api->m_appr_mgr.a_apl_acc_pat_pattern, sPattern);
				break;
			}
		}

		if(sPattern.IsEmpty())// не нашли, может не загружено?
		{
			CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
			ld.AddQuery(_T('e'),  0, m_api->m_appr_mgr.e_apl_acc_pat,0, true,true);
			if (!ld.LoadEx(true, 0, APL_T("Чтение шаблонов")))
			{
				if(m_api->m_data.GetLastAplError()!=APL_SOCK_OPERATION_IN_PROGRESS)
					AfxMessageBox(APL_T("Ошибка при загрузке шаблонов доступа."),MB_OK|MB_ICONSTOP);
			}

			bLoad= true;
		}
	}
	
	if(!sPattern.IsEmpty())
	{
		aplExtent tempInExt;
		LongArray arrayIn;
		
		GetVariant<LongArray, long>(instances, arrayIn);
		for(int i=0; i<arrayIn.GetSize(); ++i)
		{
			tempInExt.Add((CaplInstance*)arrayIn[i]);
		}
		
		if(m_api->m_data.NET_SetAccessFromPattern(&tempInExt, sPattern, APL_T("Установка доступа по шаблону ")+sPatName))
			result->boolVal= (short)0xffff;		
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::IsConnected(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	if(m_api->m_data.IsConnected())
		result->boolVal= (short)0xffff;		

	return S_OK;
}


STDMETHODIMP CAplPssAPI::ClearData(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	result->vt=VT_BOOL; 
	result->boolVal= (short)0xffff;
	m_api->m_data.ClearData();
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetCurrentPerson(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_appr_mgr.GetCurrentPerson();	
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetInstanceById(long id, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CaplInstance* inst= NULL, *inst1;

	for(int i= 0; i<m_api->m_data.instances.Size; i++)
	{
		inst1= m_api->m_data.instances.GetAt(i);
		if(inst1)
		{
			if(inst1->GetId()==id) {inst= inst1; break;}
		}
	}
	 
	if(!inst)
	{
		CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
		aplExtent ext;

		ld.AddQuery(_T('a'), (long)id, (long)0, (long)0, true);
		ld.LoadEx(true, &ext);
		if(ext.GetSize())inst= ext.GetAt(0);
	}

	result->vt=VT_I4; 
	result->lVal= (long)inst;
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadExtentInfo(VARIANT ext, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempInExt, tempChrExt;
	LongArray arrayIn;
	
	GetVariant<LongArray, long>(ext, arrayIn);

	if(m_api->m_data.m_CurSchema==_T("apl_tgb_a"))
	{
		tempInExt.Unique=false;
		for(int i=0; i<arrayIn.GetSize(); ++i)
		{
			CaplInstance* inst= (CaplInstance*)arrayIn[i];
			tempInExt.Add(inst);
		}
		if(m_api->LoadExtentInfoPrimitive(tempInExt)) result->boolVal= (short)0xffff;

		return S_OK;
	}

	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		CaplInstance* inst= (CaplInstance*)arrayIn[i];

		if(!inst || !inst->GetId() || !inst->GetType()) continue;

		if(m_api->m_data.IsKindOf(inst, m_api->m_charact_mgr.e_apl_charact_value))
			tempChrExt.Add(inst);
		else
			tempInExt.Add(inst);
	}
	
	bool bRes1= true, bRes2= true;
	if(tempInExt.GetSize())bRes1= m_api->LoadExtentInfo(tempInExt);
	if(tempChrExt.GetSize()) bRes2= m_api->m_charact_mgr.LoadCharacteristic(tempChrExt);

	if(bRes1 && bRes2)
		result->boolVal= (short)0xffff;
	
	return S_OK;
}

/************************************************************************/
/*                  Autorization                                        */
/************************************************************************/
STDMETHODIMP CAplPssAPI::LoadOrgStruct(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	m_api->m_appr_mgr.LoadDictionary();
	
	if(m_api->m_appr_mgr.LoadOrgStruct())
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateApproval(long instObject, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_appr_mgr.CreateApproval((CaplInstance*) instObject);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateApprovalEx(long instObject, long status, BSTR role, 
										  long person, long apprOwner,
										  BSTR level, DATE apprDate, 
										  BSTR signSystem, BSTR key, BSTR password, 
										  VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
		
	CString
		sRole(role),
		sLevel(level),
		sSystem(signSystem),
		sKey(key),
		sPassword(password),
		sDate;

	COleDateTime odt(apprDate);

	aplDate2String(odt, sDate);
	result->vt= VT_I4;
	result->lVal= (long)m_api->m_appr_mgr.CreateApproval(
		(CaplInstance*) instObject, (CaplInstance*)status, sLevel, 
		(CaplInstance*)person, (CaplInstance*)apprOwner,
		sRole, sDate, sSystem, sKey, sPassword);
	
	return S_OK;
}


STDMETHODIMP CAplPssAPI::SignDocument(long doc, 
									  BSTR system, BSTR key, BSTR password, 
									  BSTR *sign, BSTR *hash, BSTR *openKey, 
									  VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString 
		sSystem(system),
		sKey(key),
		sPassword(password),
		sSign, sHash, sOpenKey,
		sOwner,sCert,sInventory,sSnapShot;

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_appr_mgr.SignObject((CaplInstance*)doc, 
		sSystem, sSign, sHash, sOpenKey,sOwner,sCert,sInventory,sSnapShot);

#ifdef _UNICODE
	*sign= W2BSTR(LPCWSTR(sSign));
	*hash= W2BSTR(LPCWSTR(sHash));
	*openKey=W2BSTR(LPCWSTR(sOpenKey));
#else
	*sign= A2BSTR(LPCSTR(sSign));
	*hash= A2BSTR(LPCSTR(sHash));
	*openKey=A2BSTR(LPCSTR(sOpenKey));
#endif
	return S_OK;
}

STDMETHODIMP CAplPssAPI::CheckApproval(long approval, BOOL bShowResult, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	bool bShowRes= false;
	if(bShowResult) bShowRes= true;

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_appr_mgr.CheckApproval((CaplInstance*) approval, bShowRes);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::ShowApproval(long approval, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	if(m_api->m_appr_mgr.ShowApproval((CaplInstance*)approval))
		result->boolVal= (short)0xffff;

	return S_OK;
}


STDMETHODIMP CAplPssAPI::GetPersonName(long personOrOrg, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
	
	result->vt=VT_BSTR;
	
	CString sName;
	m_api->m_appr_mgr.GetPersonName((CaplInstance*)personOrOrg, sName);
	if(!sName.IsEmpty())
	{
#ifdef _UNICODE
		result->bstrVal= W2BSTR(LPCWSTR(sName));
#else
		result->bstrVal= A2BSTR(LPCSTR(sName));
#endif
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetPersonOfficials(long person, VARIANT *officials, BOOL bOwner, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	bool bAsOwner= true;
	if(!bOwner) bAsOwner= false;

	aplExtent ext;
	LongArray tempArray;

	if(m_api->m_appr_mgr.GetPersonOfficials((CaplInstance*)person, ext, bAsOwner))
	{
		result->boolVal= (short)0xffff;		
		for(int i= 0; i<ext.GetSize(); i++)
		{
			tempArray.Add((long)ext[i]);
		}
		FillVariant<LongArray, long>(officials, tempArray, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::ShowPersonOfficials(long person, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	m_api->m_appr_mgr.ShowPersonOfficials((CaplInstance*)person);
	result->boolVal= (short)0xffff;		

	return S_OK;
}

STDMETHODIMP CAplPssAPI::ShowOfficialHistory(long official, long showMode, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	m_api->m_appr_mgr.ShowOfficialHistory((CaplInstance*)official, showMode);
	result->boolVal= (short)0xffff;		

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SelectPersonsOrganizations(long mode, BSTR sDialogTitle, BSTR sTreeTitle, 
								VARIANT *persOrOrgs, 
								BOOL bShowUserWG, BOOL bRecursiveSelect, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	aplExtent ext;
	LongArray tempArray;

	bool bShowWG= true;
	if(!bShowUserWG) bShowWG= false;

	bool bTraverse= true;
	if(!bRecursiveSelect) bTraverse= false;
	
	CString sTitle(sDialogTitle), sTrTitle(sTreeTitle);

	if(m_api->m_appr_mgr.SelectPersonsOrganizations(mode, ext, bShowWG, 
		bTraverse, sTitle, sTrTitle))
	{
		result->boolVal= (short)0xffff;		
		for(int i= 0; i<ext.GetSize(); i++)
		{
			tempArray.Add((long)ext[i]);
		}
		FillVariant<LongArray, long>(persOrOrgs, tempArray, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SelectPersonOrOrganization(long mode, BSTR sDialogTitle, BSTR sTreeTitle, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sTitle(sDialogTitle), sTrTitle(sTreeTitle);
	
	aplExtent ext;

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_appr_mgr.SelectPersonOrOrganization(mode, ext, sTitle, sTrTitle);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadItemApproval(long item, VARIANT *allApprovals, 
												 VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	aplExtent ext;
	LongArray tempArray;
	
	if(m_api->m_appr_mgr.LoadItemApproval((CaplInstance*)item, ext))
	{
		result->boolVal= (short)0xffff;		
		for(int i= 0; i<ext.GetSize(); i++)
		{
			tempArray.Add((long)ext[i]);
		}
		FillVariant<LongArray, long>(allApprovals, tempArray, VT_I4);		
	}

	return S_OK;
}

/************************************************************************/
/*                             BProcess                                 */
/************************************************************************/
STDMETHODIMP CAplPssAPI::CreateBP(BSTR id, BSTR name, long type, long baseBP, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sId(id), 
	sName(name);

	CaplInstance* bpType= (CaplInstance*)type;
	CaplInstance* base= (CaplInstance*)baseBP;

/*	CaplAggr tempAggr;
	LongArray arrayIn;
	
	GetVariant<LongArray, long>(context, arrayIn);

	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		tempAggr.Add((CaplInstance*)arrayIn[i]);
	}*/
	
	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_bp_mgr.CreateBP(base, NULL, 
		sId, sName, bpType, APL_MODE_CREATE_BP, NULL, NULL);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateBPVersion(long bp, BSTR verId, BOOL bSetActive, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	bool bMakeActive= true;
	if(!bSetActive) bMakeActive= false;
	CaplInstance* bpInst= (CaplInstance*)verId;
	CString sId(verId);

	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_bp_mgr.CreateBPVersion(bpInst, sId, bMakeActive);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::MakeBPVersionActive(long bpVersion, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
		
	result->vt=VT_BOOL; 
	result->boolVal= 0;

	CaplInstance* inst= (CaplInstance*)bpVersion;
	
	if(m_api->m_bp_mgr.MakeBPVersionActive(inst))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteBP(long bp, BOOL bDelSubBP, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	CaplInstance* inst= (CaplInstance*)bp;
	bool bDel= true;
	if(!bDelSubBP) bDel= false;
	
	if(m_api->m_bp_mgr.DeleteBP(inst, bDel))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadBPInfo(long bp, BOOL bLoadSubBPInfo, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	CaplInstance* inst= (CaplInstance*) bp;
	bool bSubLoad= true;
	if(!bLoadSubBPInfo) bSubLoad= false;

	if(m_api->m_bp_mgr.LoadBPInfo(inst, bSubLoad))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindBPById(BSTR id, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sId(id);
	
	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_bp_mgr.FindBPById(sId);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::ShowBPProperties(long bp, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	CaplInstance* inst= (CaplInstance*)bp;

	if(m_api->m_bp_mgr.ShowBPProperties(inst))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::WhereUsedBP(long bp, VARIANT *objects, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	aplExtent tempOutExt;
	LongArray arrayOut;

	CaplInstance* inst= (CaplInstance*)bp;

	if(m_api->m_bp_mgr.WhereUsedBP(inst, tempOutExt))
	{
		result->boolVal= (short)0xffff;

		for (int i= 0; i<tempOutExt.GetSize(); ++i)
		{
			arrayOut.Add((long)tempOutExt[i]);
		}
	}
	
	CaplAttrValue tst_values[2];
	tst_values[0].value.Set(inst);
	tst_values[0].attr= m_api->m_bp_mgr.a_bp_inst_ref_process;

	aplExtent ext;
	m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_bp_mgr.e_bp_inst_ref, 1, &tst_values[0], ext, true);

	CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
	int i;
	for(i=0; i<ext.GetSize(); i++)
		ld.AddQuery(0, ext[i]);
	if(i!=0)
	{
		ld.AddQuery(_T('d'), 0, 0, m_api->m_bp_mgr.a_bp_inst_ref_item, true, true);
		ld.LoadEx();
	}
	
	if(ext.GetSize())
	{
		result->boolVal= (short)0xffff;
		
		for(i= 0; i<ext.GetSize(); i++)
		{
			CaplInstance* ref_obj;
			m_api->m_data.GetAttr(ext[i], m_api->m_bp_mgr.a_bp_inst_ref_item, ref_obj);
			arrayOut.Add((long)ref_obj);
		}
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindAssociatedBP(long instance, VARIANT *ext, VARIANT *rels, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	aplExtent tempOutExt, tempOutRels;
	LongArray arrayOut, arrayRels;

	CaplInstance* inst= (CaplInstance*)instance;
	if(m_api->m_bp_mgr.FindAssociatedBP(inst, tempOutExt, tempOutRels))
	{
		result->boolVal= (short)0xffff;
		int i;
		for (i= 0; i<tempOutExt.GetSize(); ++i)
		{
			arrayOut.Add((long)tempOutExt[i]);
		}
		FillVariant<LongArray, long>(ext, arrayOut, VT_I4);
		
		for (i= 0; i<tempOutRels.GetSize(); ++i)
		{
			arrayRels.Add((long)tempOutRels[i]);
		}
		FillVariant<LongArray, long>(rels, arrayRels, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateBPAssociation(long instance, long bp, BSTR assocId, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CaplInstance* inst= (CaplInstance*) instance,
		*bpInst= (CaplInstance*)bp;

	CString sId(assocId);

	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_bp_mgr.CreateAssociation(inst, bpInst, sId);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindBPAssociation(long instance, long bp, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CaplInstance* inst= (CaplInstance*) instance,
		*bpInst= (CaplInstance*)bp;

	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadAllBPResources(long bp, VARIANT *resources, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	aplExtent tempOutExt;
	LongArray arrayOut;

	CaplInstance* inst= (CaplInstance*)bp;

	if(m_api->m_bp_mgr.LoadAllBPResources(inst, tempOutExt))
	{
		result->boolVal= (short)0xffff;

		for (int i= 0; i<tempOutExt.GetSize(); ++i)
		{
			arrayOut.Add((long)tempOutExt[i]);
		}
		FillVariant<LongArray, long>(resources, arrayOut, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetAllBPVersion(long bp, VARIANT *versions, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	aplExtent tempOutExt;
	LongArray arrayOut;

	CaplInstance* inst= (CaplInstance*)bp;

	if(m_api->m_bp_mgr.GetAllBPVersion(inst, tempOutExt))
	{
		result->boolVal= (short)0xffff;

		for (int i= 0; i<tempOutExt.GetSize(); ++i)
		{
			arrayOut.Add((long)tempOutExt[i]);
		}
		FillVariant<LongArray, long>(versions, arrayOut, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::AddBPToBP(long subBP, long baseBp, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	CaplInstance* sub= (CaplInstance*)subBP, *base= (CaplInstance*)baseBp;

	if(m_api->m_bp_mgr.AddBPToBP(sub, base))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteBPRelation(long subBP, long baseBP, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; result->boolVal= 0;
	CaplInstance* sub= (CaplInstance*)subBP, *base= (CaplInstance*)baseBP;
	if(m_api->m_bp_mgr.DeleteBPRelation(sub, base)) result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadBPDictionary(VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; result->boolVal= 0;
	if(m_api->m_bp_mgr.LoadDictionary()) result->boolVal= (short)0xffff;
	return S_OK;
}

/************************************************************************/
/*                           Category                                   */
/************************************************************************/
STDMETHODIMP CAplPssAPI::FindCategory(BSTR id, 
										 /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sId(id);	
	result->vt= VT_I4;
	result->lVal= (long)(m_api->m_categ_mgr.FindCateg(sId));
	return S_OK;
}

STDMETHODIMP CAplPssAPI::InsertSubCategory(long baseCategory, long subCategory, 
											  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	bool bRes= m_api->m_categ_mgr.InsertSubCategory
		((CaplInstance*)baseCategory, (CaplInstance*)subCategory);
	if(bRes)
		result->boolVal= 1;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::RemoveSubCategory(long baseCategory, long subCategory, 
											  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	bool bRes= m_api->m_categ_mgr.RemoveSubCategory
		((CaplInstance*)baseCategory, (CaplInstance*)subCategory);
	result->boolVal= 1;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateCategory(BSTR id, BSTR name, BSTR description, 
										   /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sId(id),
		sName(name),
		sDescription(description);
	
	result->vt= VT_I4;
	result->lVal= (long)(m_api->m_categ_mgr.CreateCategory(sId, sName, sDescription));
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetCategoryAttr(long category, 
											BSTR *id, BSTR *name, BSTR *description, 
											/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	CString sId,
		sName,
		sDscr;
	
	bool bRes= m_api->m_categ_mgr.GetCategoryAttr((CaplInstance*)category, sId, sName, sDscr);	
	
	if(bRes)
	{
#ifdef _UNICODE
		*id= W2BSTR(LPCWSTR(sId));
		*name= W2BSTR(LPCWSTR(sName));
		*description= W2BSTR(LPCWSTR(sDscr));
#else
		*id= A2BSTR(LPCSTR(sId));
		*name= A2BSTR(LPCSTR(sName));
		*description= A2BSTR(LPCSTR(sDscr));
#endif
		result->boolVal= 1;
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetAllSubCategory(long category, VARIANT *subCategories, 
											  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent extent, rels;
	CArray<long, long> array;

	bool bRes= m_api->m_categ_mgr.GetAllSubCategory2((CaplInstance*)category, extent, rels);
	
	if(bRes)
	{
		result->boolVal= 1;

		for (long i= 0; i<extent.GetSize(); ++i)
			array.Add((long)extent[i]);
		
		FillVariant<LongArray, long>(subCategories, array, VT_I4);	
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::RemoveCategory(long category, /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_categ_mgr.RemoveCategory((CaplInstance*)category);

	result->boolVal= 1;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetAllParentCategory(long category, VARIANT *parentCategories, 
												 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	aplExtent extent;
	LongArray array;
	
	bool bRes= m_api->m_categ_mgr.GetAllParentCategory((CaplInstance*)category, extent);
	
	if(bRes)
	{
		result->boolVal= 1;

		for (long i= 0; i<extent.GetSize(); ++i)
			array.Add((long)extent[i]);

		FillVariant<LongArray, long>(parentCategories, array, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetCategoryContents(long category, VARIANT *extent, BOOL all, 
												/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempExtent;
	bool bAll;
	LongArray array;
	if(!all)
		bAll= false;
	else
		bAll= true;

	bool bRes= m_api->m_categ_mgr.GetCategoryContents((CaplInstance*)category, tempExtent, bAll);
	
	if(bRes)
	{
		result->boolVal= 1;

		for (long i= 0; i<tempExtent.GetSize(); ++i)
			array.Add((long)tempExtent[i]);

		FillVariant<LongArray, long>(extent, array, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindProductInCategory(long product, long category, BOOL all, 
												  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bAll;
	if(!all)
		bAll= false;
	else
		bAll= true;

	bool bRes= m_api->m_categ_mgr.FindProductInCategory((CaplInstance*)product, 
		(CaplInstance*)category, bAll);

	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::AddProductToCategory(long product, long category, 
												 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_categ_mgr.AddPrdToCategory((CaplInstance*)product, (CaplInstance*)category);

	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::RemoveProductFromCategory(long product, long category, 
													  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_categ_mgr.RemovePrdFromCategory((CaplInstance*)product, (CaplInstance*)category);
	
	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetProductCategories(long product, VARIANT *extent, 
												 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempExtent;
	LongArray array;

	bool bRes= m_api->m_categ_mgr.GetProductCategories((CaplInstance*)product, tempExtent);
	
	if(bRes)
	{
		result->boolVal= 1;

		for (long i= 0; i<tempExtent.GetSize(); ++i)
			array.Add((long)tempExtent[i]);

		FillVariant<LongArray, long>(extent, array, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetAllCategoryVersion(long categ, VARIANT* versions, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
	
	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempOutExt;
	LongArray arrayOut;

	CaplInstance* inst= (CaplInstance*)categ;

	if(m_api->m_categ_mgr.GetAllCategoryVersion(inst, tempOutExt))
	{
		result->boolVal= (short)0xffff;

		for (int i= 0; i<tempOutExt.GetSize(); ++i)
		{
			arrayOut.Add((long)tempOutExt[i]);
		}
		FillVariant<LongArray, long>(versions, arrayOut, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadCategoryInfo(long categ, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
	
	result->vt=VT_BOOL; 
	result->boolVal= 0;

	CaplInstance* inst= (CaplInstance*)categ;
	
	if(m_api->m_categ_mgr.LoadCategoryInfo(inst))
		result->boolVal= (short)0xffff;

	return S_OK;
}

/************************************************************************/
/*                          Characteristic                              */
/************************************************************************/

STDMETHODIMP CAplPssAPI::GetCharacteristicById(BSTR id, 
														/*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sId(id);	
	result->vt= VT_I4;
	result->lVal= (long)m_api->m_charact_mgr.GetCharacteristicById(sId);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetInstCharacteristic(long instance, long characteristic, 
														/*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_charact_mgr.GetInstCharacteristic((CaplInstance*) instance, 
		(CaplInstance*) characteristic);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindAssociatedCharacteristic(long instance, 
														  VARIANT *outExt, VARIANT *outGroup, 
														  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempOutExt,
		tempOutGroup;
	LongArray arrayGroup, 
		arrayExt;

	bool bRes= m_api->m_charact_mgr.FindAssociatedCharacteristic((CaplInstance*) instance,
		tempOutExt, tempOutGroup);
	
	if(bRes)
	{
		result->lVal= 1;
		long i;
		for (i= 0; i<tempOutGroup.GetSize(); ++i)
		{
			arrayGroup.Add((long)tempOutGroup[i]);
		}	
		for (i= 0; i<tempOutExt.GetSize(); ++i)
		{
			arrayExt.Add((long)tempOutExt[i]);
		}
		FillVariant<LongArray, long>(outGroup, arrayGroup, VT_I4);
		FillVariant<LongArray, long>(outExt, arrayExt, VT_I4);	
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetCharacteristicType(BSTR type, 
														/*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sType(type);
	result->vt= VT_I4;
	result->lVal= (long)m_api->m_charact_mgr.GetCharacteristicType(sType);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateDescriptiveCharacteristic(long item, 
																  long characteristic, 
																  long type, BSTR value, 
																  /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sValue(value);
	result->vt= VT_I4;
	result->lVal= (long)m_api->m_charact_mgr.CreateDescriptiveCharacteristic((CaplInstance*)item, 
		(CaplInstance*)characteristic, (CaplInstance*)type, sValue);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateMeasuredCharacteristic(long item, 
															   long characteristic, 
															   long type, double value, 
															   double maxDeviation, 
															   double minDeviation, 
															   /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_charact_mgr.CreateMeasuredCharacteristic((CaplInstance*)item, 
		(CaplInstance*)characteristic, (CaplInstance*)type, value, 
		maxDeviation, minDeviation);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateDateTimeCharacteristic(long item, long characteristic, long type, DATE value, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CaplInstance* charact= (CaplInstance*)characteristic;
	CaplInstance* inst= (CaplInstance*)item;

	result->vt= VT_I4;
	result->lVal= 0;

	if(!charact || !item) return S_OK;
	if(charact)
	{
		CaplInstance* unit= NULL;
		m_api->m_data.GetAttr(unit, m_api->m_charact_mgr.a_apl_charact_unit, unit);
		if(!unit || !m_api->m_data.IsKindOf(unit, m_api->m_charact_mgr.e_apl_time_unit))
		{
			MessageBox(APL_T("Ошибочные данные."), APL_T("Создание характеристики"), MB_OK|MB_ICONERROR);
			return S_OK;
		}
	}

	COleDateTime odt(value);
	CString sVal;
	aplDate2String(odt, sVal);

	result->lVal= (long)m_api->m_charact_mgr.CreateDateTimeCharacteristic
		(inst, charact, (CaplInstance*)type, sVal);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadCharacteristicDictionary(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	if(m_api->m_charact_mgr.LoadDictionary())
	{
		result->boolVal= (short)0xffff;	
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetUnitById(BSTR name, 
								  VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sName(name);

	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_charact_mgr.GetUnitById(sName);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateCharacteristic(long item, long base_val, 
										   long new_char, long *val, 
										   VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	CaplInstance* inst1;
	if(m_api->m_charact_mgr.CreateCharacteristic((CaplInstance*) item, 
		(CaplInstance*) base_val, &inst1, (CaplInstance*)new_char))
	{
		*val= (long)inst1;

		result->boolVal= (short)0xffff;	
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteCharacteristic(long val, 
										   VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	if(m_api->m_charact_mgr.DeleteCharacteristic((CaplInstance*) val))
	{
		result->boolVal= (short)0xffff;	
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetUnitName(long unit, BSTR *name, 
								  VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
	
	CString sName;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	if(m_api->m_charact_mgr.GetUnitName((CaplInstance*) unit, sName))
	{
#ifdef _UNICODE
		*name= W2BSTR(LPCWSTR(sName));
#else
		*name= A2BSTR(LPCSTR(sName));
#endif
		result->boolVal= (short)0xffff;	
	}
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::PrintCharacteristicValue(long value, long unit, BSTR *name, 
											   VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
	
	CString sName;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	if(m_api->m_charact_mgr.PrintCharacteristicValue((CaplInstance*) value, (CaplInstance*) unit, sName))
	{
#ifdef _UNICODE
		*name= W2BSTR(LPCWSTR(sName));
#else
		*name= A2BSTR(LPCSTR(sName));
#endif
		result->boolVal= (short)0xffff;	
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateCopyCharacteristicVal(long old_instance, long new_instance, 
												  VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_charact_mgr.CreateCopyCharacteristicVal((CaplInstance*)old_instance, (CaplInstance*)new_instance);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SelectCharactUnionGroup(long defaultCharactUnion, long defaultCharactGroup, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CaplInstance *charUnion= (CaplInstance*) defaultCharactUnion,
			*group= (CaplInstance*) defaultCharactGroup;

	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_charact_mgr.SelectCharactUnionGroup(charUnion, group);
	
	return S_OK;
}


STDMETHODIMP CAplPssAPI::SelectCharacteristic(long defaultCharact, long defaultGroup, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CaplInstance *charact= (CaplInstance*) defaultCharact,
			*group= (CaplInstance*) defaultGroup;

	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_charact_mgr.SelectCharacteristic(charact, group);
	
	return S_OK;
}

/************************************************************************/
/*                             Document                                 */
/************************************************************************/
STDMETHODIMP CAplPssAPI::FindDocById(BSTR id, 
										/*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sId(id);

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_doc_mgr.FindDocById(sId);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadDocumentDictionary(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	if(m_api->m_doc_mgr.LoadDictionary())
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetDocumentTypeBN(BSTR type, 
											  /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sType(type);

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_doc_mgr.GetDocumentTypeBN(sType);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetFileName(long docOrRevision, BSTR* buf, 
										/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sBuf;
	
	bool bRes= m_api->m_doc_mgr.GetFileName((CaplInstance*)docOrRevision, sBuf);

#ifdef _UNICODE
		*buf= W2BSTR(LPCWSTR(sBuf));
#else
		*buf= A2BSTR(LPCSTR(sBuf));
#endif

	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetFullFileName(long docOrRevision, BSTR* buf, 
											/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	CString sBuf;	
	
	bool bRes= m_api->m_doc_mgr.GetFullFileName((CaplInstance*)docOrRevision, sBuf);

#ifdef _UNICODE
		*buf= W2BSTR(LPCWSTR(sBuf));
#else
		*buf= A2BSTR(LPCSTR(sBuf));
#endif
	
	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateDocument(BSTR id, BSTR name, BSTR description, 
										   long type, BSTR path, BOOL stored, 
										   /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sId(id),
		sName(name),
		sDescription(description),
		sPath(path);

	bool bStored;
	if(!stored)
		bStored= false;
	else
		bStored= true;			

	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_doc_mgr.CreateDocument(sId, sName, sDescription, 
		(CaplInstance*)type, sPath, bStored);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadRevision(long docOrRevision, BSTR path, 
										 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	CString sPath(path);
	
	bool bRes= m_api->m_doc_mgr.LoadRevision((CaplInstance*)docOrRevision, sPath);
	
	if(bRes)
		result->boolVal= 1;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::View(long docOrRevision, 
								 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_doc_mgr.View((CaplInstance*)docOrRevision);
	
	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::Edit(long docOrRevision, 
								 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_doc_mgr.Edit((CaplInstance*)docOrRevision,0);
	
	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindAssociatedDocuments(long instance, 
											VARIANT *outExt, VARIANT *outRel, 
											/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempOutExt, 
		tempOutRel;
	LongArray arrayExt, 
		arrayRel;	

	bool bRes= m_api->m_doc_mgr.FindAssociatedDocuments((CaplInstance*)instance, tempOutExt, tempOutRel);
	
	if(bRes)
	{
		result->boolVal= 1;
		long i;
		for (i= 0; i<tempOutExt.GetSize(); ++i)
		{
			arrayExt.Add((long)tempOutExt[i]);
		}	
		FillVariant<LongArray, long>(outExt, arrayExt, VT_I4);
		
		for (i= 0; i<tempOutRel.GetSize(); ++i)
		{
			arrayRel.Add((long)tempOutRel[i]);
		}
		FillVariant<LongArray, long>(outRel, arrayRel, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteDoc(long doc, 
									  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_doc_mgr.DeleteDoc((CaplInstance*)doc);
	
	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateAssociation(long instance, long doc, 
											  /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_doc_mgr.CreateAssociation((CaplInstance*)instance, (CaplInstance*)doc);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindAssociation(long instance, long doc, 
											/*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_doc_mgr.FindAssociation((CaplInstance*)instance, (CaplInstance*)doc);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadDocInfo(long doc, 
										/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	bool bRes= m_api->m_doc_mgr.LoadDocInfo((CaplInstance*)doc);
	
	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadAllDocumentRevision(long doc, VARIANT *revExt, 
													/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempRevExt;
	LongArray arrayRev;	

	bool bRes= m_api->m_doc_mgr.LoadAllDocumentRevision((CaplInstance*)doc, tempRevExt);
	
	if(bRes)
	{
		result->boolVal= 1;

		for (long i= 0; i<tempRevExt.GetSize(); ++i)
		{
			arrayRev.Add((long)tempRevExt[i]);
		}	
		FillVariant<LongArray, long>(revExt, arrayRev, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::ShowDocumentProperties(long docOrRevision, 
												   /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_doc_mgr.ShowDocProperties((CaplInstance*)docOrRevision);
	
	if(bRes)
		result->boolVal= 1;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteRevision(long revision, 
										   /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_doc_mgr.DeleteRevision((CaplInstance*)revision);
	
	if(bRes)
		result->boolVal= 1;

	return S_OK;
}


STDMETHODIMP CAplPssAPI::SelectDocType(long selectedDocType, long selectedDocGroup, VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CaplInstance *docType= (CaplInstance*) selectedDocType,
			*group= (CaplInstance*) selectedDocGroup;

	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_doc_mgr.SelectDocType(docType, group);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateDocumentRevision(long document, BSTR path, BOOL stored, BOOL setActive, long baseRevision, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CaplInstance* doc= (CaplInstance*)document, 
		*baseRev= (CaplInstance*)baseRevision;
	bool bStored= true;
	if(!stored) bStored= false;
	bool bSetActive= false;
	if(setActive) bSetActive= true;
	CString sPath(path);


	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_doc_mgr.CreateDocumentRevision(doc, sPath, bStored, 
		bSetActive, baseRev);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateFile(BSTR path, BOOL stored, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	bool bStored= true;
	if(!stored) bStored= false;
	CString sPath(path);
	
	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_doc_mgr.CreateFile(sPath, bStored);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::ShowDocChanges(long document, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	CaplInstance* doc= (CaplInstance*)document;

	if(m_api->m_doc_mgr.ShowDocChanges(doc))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CheckSubDocument(long docOrRevision, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CaplInstance* doc= (CaplInstance*)docOrRevision;
	
	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_doc_mgr.CheckSubDocument(doc);

	return S_OK;
}

/************************************************************************/
/*                             Folder                                   */
/************************************************************************/
STDMETHODIMP CAplPssAPI::LoadFolderInfo(long folder, 
										 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_folder_mgr.LoadFolderInfo((CaplInstance*)folder);

	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetAllSubFolder(long folder, VARIANT *subFolders, 
										  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent subFolderExt;
	LongArray subFolderArr;
	
	bool bRes= m_api->m_folder_mgr.GetAllSubFolder((CaplInstance*)folder, subFolderExt);

	if(bRes)
	{
		result->boolVal= 1;

		for(int i=0; i<subFolderExt.GetSize(); ++i)
		{
			subFolderArr.Add((long)subFolderExt[i]);
		}
		FillVariant<LongArray, long>(subFolders, subFolderArr, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateFolder(long parentFolder, BSTR name, BSTR description, 
									   /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sName(name),
		sDescription(description);
	
	result->vt=VT_I4;
	result->lVal= (long)m_api->m_folder_mgr.CreateFolder((CaplInstance*)parentFolder, sName, sDescription);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteFolder(long folder, 
									   /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_folder_mgr.DeleteFolder((CaplInstance*)folder);

	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetFolderContents(long folder, VARIANT *folderContents, 
											/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent contentsExt;
	LongArray contentsArr;

	bool bRes= m_api->m_folder_mgr.GetFolderContents((CaplInstance*)folder, contentsExt);

	if(bRes)
	{
		result->boolVal= 1;

		for(int i=0; i<contentsExt.GetSize(); ++i)
		{
			contentsArr.Add((long)contentsExt[i]);
		}
		FillVariant<LongArray, long>(folderContents, contentsArr, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::AddToFolder(long folder, long item, 
									  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_folder_mgr.AddToFolder((CaplInstance*) folder, (CaplInstance*)item);

	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::RemoveFromFolder(long folder, long item, 
										   /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	bool bRes= m_api->m_folder_mgr.RemoveFromFolder((CaplInstance*)folder, (CaplInstance*)item);

	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::ShowFolderProperties(long folder, 
											   /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_folder_mgr.ShowFolderProperties((CaplInstance*)folder);

	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::MoveFolder(long folder, long parentFolder, 
									 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_folder_mgr.MoveFolder((CaplInstance*)folder, (CaplInstance*)parentFolder);

	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindFolderByName(BSTR name, long parentFolder, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
	
	CString sName(name);

	result->vt=VT_I4;
	result->lVal= (long)m_api->m_folder_mgr.FindFolderByName(sName, (CaplInstance*)parentFolder);	

	return S_OK;
}

/************************************************************************/
/*                           Product                                    */
/************************************************************************/
STDMETHODIMP CAplPssAPI::LoadAllSubProduct(long ci, long context, long pdf, 
											 VARIANT *extRel, VARIANT *extPdf, 
											 BOOL fromBase, 
											 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempExtRel, 
		tempExtPdf;
	LongArray arrayRel, 
		arrayPdf;
	bool sFromBase;

	if(fromBase)
		sFromBase= true;
	else
		sFromBase= false;

	bool bRes= m_api->m_prd_mgr.LoadAllSubProduct((CaplInstance*)ci, (CaplInstance*)context, 
		(CaplInstance*)pdf, tempExtRel, tempExtPdf, sFromBase);
	
	if(bRes)
	{
		result->boolVal= 1;
		long i;
		for (i= 0; i<tempExtRel.GetSize(); ++i)
		{
			arrayRel.Add((long)tempExtRel[i]);
		}	
		FillVariant<LongArray, long>(extRel, arrayRel, VT_I4);
		
		for (i= 0; i<tempExtPdf.GetSize(); ++i)
		{
			arrayPdf.Add((long)tempExtPdf[i]);
		}
		FillVariant<LongArray, long>(extPdf, arrayPdf, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::FilterlBySN(VARIANT inExt, BSTR sn, VARIANT *outExt, 
									   /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempInExt, 
		tempOutExt;
	LongArray arrayIn, 
		arrayOut;
	CString sSn(sn);
	int i;

	GetVariant<LongArray, long>(inExt, arrayIn);
	for(i=0; i<arrayIn.GetSize(); ++i)
	{
		tempInExt.Add((CaplInstance*)arrayIn[i]);
	}

	bool bRes= m_api->m_prd_mgr.FilterlBySN(tempInExt, sSn, tempOutExt);
	
	if(bRes)
	{
		result->boolVal= 1;

		for (i= 0; i<tempOutExt.GetSize(); ++i)
		{
			arrayOut.Add((long)tempOutExt[i]);
		}
		FillVariant<LongArray, long>(outExt, arrayOut, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::FilterlByDate(VARIANT inExt, DATE time, VARIANT *outExt, 
										 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempInExt, 
		tempOutExt;
	LongArray arrayIn, 
		arrayOut;
	COleDateTime otime;
	int i;
	
	GetVariant<LongArray, long>(inExt, arrayIn);
	for(i=0; i<arrayIn.GetSize(); ++i)
	{
		tempInExt.Add((CaplInstance*)arrayIn[i]);
	}

	otime= time;
	
	bool bRes= m_api->m_prd_mgr.FilterlByDate(tempInExt, otime, tempOutExt);
	
	if(bRes)
	{
		result->boolVal= 1;

		for (i= 0; i<tempOutExt.GetSize(); ++i)
		{
			arrayOut.Add((long)tempOutExt[i]);
		}
		FillVariant<LongArray, long>(outExt, arrayOut, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetAllProductVersion(long prd, VARIANT *outExt, 
												/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempOutExt;
	LongArray arrayOut;
	
	bool bRes= m_api->m_prd_mgr.GetAllProductVersion((CaplInstance*)prd, tempOutExt);
	
	if(bRes)
	{
		result->boolVal= 1;

		for (int i= 0; i<tempOutExt.GetSize(); ++i)
		{
			arrayOut.Add((long)tempOutExt[i]);
		}
		FillVariant<LongArray, long>(outExt, arrayOut, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindProductByID(BSTR id, 
										   /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString sId(id);
	
	result->vt= VT_I4;
	result->lVal= (long)m_api->m_prd_mgr.FindPrdById(sId);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindPdfByID(long product, BSTR id, 
									   /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString sId(id);
	
	result->vt= VT_I4;
	result->lVal= (long)m_api->m_prd_mgr.FindPdfById((CaplInstance*)product, sId);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadProductInfo(long instance, 
										   /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	bool bRes= m_api->m_prd_mgr.LoadPrdInfo((CaplInstance*)instance);
	
	if(bRes)
		result->boolVal= 1;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreatePDF(BSTR id, BSTR name, BSTR version, 
									 BOOL testUnique, 
									 /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString sId(id),
		sName(name),
		sVersion(version);

	bool bTestUnique= true;
	if(!testUnique)
		bTestUnique= false;

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_prd_mgr.CreatePdf(sId, sName, sVersion, bTestUnique);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreatePdfRelation(long context, long relatingPDF, long relatedPDF,
											 BSTR id, BSTR name, double count, 
											 long unit, 
											 /*long*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString sId(id),
		sName(name);

	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_prd_mgr.CreatePdfRelation((CaplInstance*)context, 
		(CaplInstance*)relatingPDF, (CaplInstance*)relatedPDF, sId, sName, 
		count, (CaplInstance*)unit);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::DisassemblyProduct(long ci, long context, long pdf, 
											  VARIANT *pdfArray, VARIANT *countArray, 
											  VARIANT *unitArray, BOOL ReturnOnlyPart, 
											  /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplInstArray tempPdfExt, 
		tempUnitExt;
	aplRealArray tempCountArray;
	LongArray extPdf,
		extUnit;
	DoubleArray arrayCount;

	bool bRetOnlyParts= true;
	if(!ReturnOnlyPart)
		bRetOnlyParts= false;
	
	bool bRes= m_api->m_prd_mgr.DisassemblyProduct((CaplInstance*) ci,
		(CaplInstance*) context, (CaplInstance*) pdf,
		tempPdfExt, tempCountArray, tempUnitExt, bRetOnlyParts);

	if(bRes)
	{
		result->boolVal= 1;
		int i;
		for(i=0; i<tempPdfExt.GetSize(); ++i)
			extPdf.Add((long)tempPdfExt[i]);
		FillVariant<LongArray, long>(pdfArray, extPdf, VT_I4);
		
		for(i=0; i<tempCountArray.GetSize(); ++i)
			arrayCount.Add((double)tempCountArray[i]);	
		FillVariant<DoubleArray, double>(countArray, arrayCount, VT_R8);
		
		for(i=0; i<tempPdfExt.GetSize(); ++i)
			extUnit.Add((long)tempUnitExt[i]);		
		FillVariant<LongArray, long>(unitArray, extUnit, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::WhereProductUsed(long pdf, 
											VARIANT *extRel, VARIANT *extPdf, 
											BOOL fromBase, 
											/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;

	aplExtent tempExtRel,
		tempExtPdf;
	LongArray arrayRel, 
		arrayPdf;

	bool bFromBase= true;
	if(!fromBase)
		bFromBase= false;

	bool bRes= m_api->m_prd_mgr.WhereUsedProduct((CaplInstance*)pdf, 
		tempExtRel, tempExtPdf, bFromBase);

	if(bRes)
	{
		result->boolVal= 1;
	
		int i;
		for(i=0; i<tempExtRel.GetSize(); ++i)
			arrayRel.Add((long)tempExtRel[i]);
		FillVariant<LongArray, long>(extRel, arrayRel, VT_I4);
		
		for(i=0; i<tempExtPdf.GetSize(); ++i)
			arrayPdf.Add((long)tempExtPdf[i]);
		FillVariant<LongArray, long>(extPdf, arrayPdf, VT_I4);
	}
	return S_OK;
}


STDMETHODIMP CAplPssAPI::LoadProductAlternates(long product, 
											VARIANT *extRel, VARIANT *extPrd, 
											VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	result->vt=VT_BOOL; 
	result->boolVal= 0;

	LongArray arrRel, arrPrd;
	aplExtent rel, prd;

	if(m_api->m_prd_mgr.LoadProductAlternates((CaplInstance*)product, rel, prd))
	{
		int i;
		for(i= 0; i<rel.GetSize(); i++)
			arrRel.Add((long)rel[i]);
		FillVariant<LongArray, long>(extRel, arrRel, VT_I4);

		for(i= 0; i<prd.GetSize(); i++)
			arrPrd.Add((long)prd[i]);
		FillVariant<LongArray, long>(extPrd, arrPrd, VT_I4);		
	
		result->boolVal= (short)0xffff;
	}
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadAllZagotov(long pdf, VARIANT *extRels, VARIANT *extPdfs, BOOL includeDesign, BOOL fromBase, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	result->vt=VT_BOOL; 
	result->boolVal= 0;
	
	bool bFromBase= true;
	if(!fromBase)
		bFromBase= false;
	bool bIncludeDesign= false;
	if(includeDesign)
		bIncludeDesign= true;

	LongArray arrRel, arrPdf;
	aplExtent extRel, extPdf;
	
	if(m_api->m_prd_mgr.LoadAllZagotov((CaplInstance*)pdf, extRel, extPdf, bIncludeDesign, bFromBase))
	{
		int i;
		for(i= 0; i<extRel.GetSize(); i++)
			arrRel.Add((long)extRel[i]);
		FillVariant<LongArray, long>(extRels, arrRel, VT_I4);

		for(i= 0; i<extPdf.GetSize(); i++)
			arrPdf.Add((long)extPdf[i]);
		FillVariant<LongArray, long>(extPdfs, arrPdf, VT_I4);		
	
		result->boolVal= (short)0xffff;		
	}

	return S_OK;
}

/************************************************************************/
/*                           Свойства и флаги                           */
/************************************************************************/

STDMETHODIMP CAplPssAPI::get_AutoSave(BOOL *pVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api) S_OK; 

	if(m_api->m_AutoSave) *pVal= TRUE;
	else *pVal= FALSE;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::put_AutoSave(BOOL newVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api) S_OK; 

	if(newVal) m_api->SetAutoSave(true);
	else m_api->SetAutoSave(false);
	
	m_api->Init();

	return S_OK;
}

STDMETHODIMP CAplPssAPI::get_ModeInteractive(BOOL *pVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api) S_OK; 

	if(m_api->m_ModeInteractive) *pVal= TRUE;
	else *pVal= FALSE;
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::put_ModeInteractive(BOOL newVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api) S_OK; 

	if(newVal) m_api->SetModeInteractive(true);
	else m_api->SetModeInteractive(false);
	
	m_api->Init();
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::put_ErrorMode(BOOL newVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	if(newVal) m_api->m_data.SetErrorMessageMode(true);
	else m_api->m_data.SetErrorMessageMode(false);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::put_WarningMode(BOOL newVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	if(newVal) m_api->m_data.SetWarningMessageMode(true);
	else m_api->m_data.SetWarningMessageMode(false);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::get_LastErrorDescription(BSTR *pVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

#ifdef _UNICODE
	*pVal= W2BSTR(LPCWSTR(m_api->m_data.GetLastErrorDescription()));
#else
	*pVal= A2BSTR(LPCSTR(m_api->m_data.GetLastErrorDescription()));
#endif

	return S_OK;
}

STDMETHODIMP CAplPssAPI::get_LastErrorCode(long *pVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	*pVal= m_api->m_data.GetLastAplError();

	return S_OK;
}

/************************************************************************/
/*                         Блокировка объектов                          */
/************************************************************************/

//для документов
STDMETHODIMP CAplPssAPI::CheckIn(long doc, BSTR path, BOOL setActive, 
									/*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; result->boolVal= 0;

	CString sPath(path);
	bool bSetActive;

	if(setActive)bSetActive= true;
	else bSetActive= false;

	bool bRes= m_api->m_doc_mgr.CheckIn((CaplInstance*)doc, sPath, bSetActive);
	if(bRes) result->boolVal= 1;

	return S_OK;
}

//для БП и характеристик
STDMETHODIMP CAplPssAPI::CheckIn(long instance, BOOL setActive, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
	
	result->vt=VT_BOOL; result->boolVal= 0;
	
	CaplInstance* inst= (CaplInstance*)instance;
//	if(!AfxIsValidAddress(inst, sizeof(CaplInstance))) return S_OK;
	
	bool bSetActive;
	if(setActive)bSetActive= true;
	else bSetActive= false;

	bool bRes;
	if(m_api->m_data.IsKindOf(inst, m_api->m_charact_mgr.e_apl_charact_value))
		bRes= m_api->m_charact_mgr.CheckIn(inst, bSetActive);
	else if(m_api->m_data.IsKindOf(inst, m_api->m_bp_mgr.e_bp))
		bRes= m_api->m_bp_mgr.CheckIn(inst, true, bSetActive);
	else return S_OK;
	
	if(bRes) result->boolVal= 1;

	return S_OK;
}

//для категорий
STDMETHODIMP CAplPssAPI::CheckIn(long categ, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
	
	result->vt=VT_BOOL; result->boolVal= 0;
	
	if(m_api->m_categ_mgr.CheckIn((CaplInstance*)categ))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CheckOut(long instance, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
	
	result->vt=VT_BOOL; result->boolVal= 0;
	
	CaplInstance* inst= (CaplInstance*) instance;
	bool bRes= false;

	if(m_api->m_data.IsKindOf(inst, m_api->m_charact_mgr.e_apl_charact_value))
		bRes= m_api->m_charact_mgr.CheckOut(inst);
	else if(m_api->m_data.IsKindOf(inst, m_api->m_categ_mgr.e_categ))
		bRes= m_api->m_categ_mgr.CheckOut(inst);

	if(bRes) result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CheckOut(long docOrRevision, BSTR path, 
									 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; result->boolVal= 0;

	CString sPath(path);
	bool bRes= m_api->m_doc_mgr.CheckOut((CaplInstance*)docOrRevision, sPath);	
	if(bRes) result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CheckOut(long bp, BOOL checkOutSubBP, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; result->boolVal= 0;

	bool bCheckoutSubBP= false;
	if(checkOutSubBP) bCheckoutSubBP= true;
	
	if(m_api->m_bp_mgr.CheckOut((CaplInstance*)bp, bCheckoutSubBP))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::UndoCheckOut(long instance, 
										 /*BOOL*/VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; result->boolVal= 0;
	bool bRes= m_api->m_doc_mgr.UndoCheckOut((CaplInstance*)instance);
	if(bRes) result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::UndoCheckOut(long bp, BOOL undoCheckOutSubBP, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;
	
	result->vt=VT_BOOL; result->boolVal= 0;
	bool bCheckoutSubBP= false;
	if(undoCheckOutSubBP) bCheckoutSubBP= true;
	
	if(m_api->m_bp_mgr.UndoCheckOut((CaplInstance*)bp, bCheckoutSubBP))
		result->boolVal= (short)0xffff;

	return S_OK;
}


STDMETHODIMP CAplPssAPI::StrConvertPdfType2Rus(BSTR sType, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt= VT_BSTR;
	CString sInStr(sType), sRetStr;	
	
	sRetStr= m_api->m_prd_mgr.StrConvertPdfType2Rus(sInStr);

#ifdef _UNICODE
	result->bstrVal= W2BSTR(LPCWSTR(sRetStr));
#else
	result->bstrVal= A2BSTR(LPCSTR(sRetStr));
#endif
	return S_OK;
}

STDMETHODIMP CAplPssAPI::StrConvertRus2PdfType(BSTR sRusType, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt= VT_BSTR;
	CString sInStr(sRusType), sRetStr;	
	
	sRetStr= m_api->m_prd_mgr.StrConvertRus2PdfType(sInStr);

#ifdef _UNICODE
	result->bstrVal= W2BSTR(LPCWSTR(sRetStr));
#else
	result->bstrVal= A2BSTR(LPCSTR(sRetStr));
#endif
	return S_OK;
}

STDMETHODIMP CAplPssAPI::StrConvertMakeOrBuy2Rus(BSTR sSource, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt= VT_BSTR;
	CString sInStr(sSource), sRetStr;	
	
	sRetStr= m_api->m_prd_mgr.StrConvertMakeOrBuy2Rus(sInStr);

#ifdef _UNICODE
	result->bstrVal= W2BSTR(LPCWSTR(sRetStr));
#else
	result->bstrVal= A2BSTR(LPCSTR(sRetStr));
#endif
	return S_OK;
}

STDMETHODIMP CAplPssAPI::StrConvertRus2MakeOrBuy(BSTR sRusSource, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt= VT_BSTR;
	CString sInStr(sRusSource), sRetStr;	
	
	sRetStr= m_api->m_prd_mgr.StrConvertRus2MakeOrBuy(sInStr);

#ifdef _UNICODE
	result->bstrVal= W2BSTR(LPCWSTR(sRetStr));
#else
	result->bstrVal= A2BSTR(LPCSTR(sRetStr));
#endif
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadSystemDictionary(BSTR schema, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	CString sSchema(schema);
	
	if(m_api->m_data.LoadDictionary(sSchema))
		result->boolVal= (short)0xffff;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadP21(BSTR sFileName, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	CString sName(sFileName);

	if(sName.IsEmpty())
	{
		CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
			_T("Step Files (*.stp; *.std; *.txt)|*.stp; *.std; *.txt|All Files (*.*)|*.*||"));
		if(dlg.DoModal()==IDOK)	sName= dlg.GetPathName();		
	}

	if(sName.IsEmpty()) return S_OK;

	aplP21Header header;
	if(m_api->m_data.LoadP21(sName, header))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SaveP21(BSTR fileName, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	CString sFileName(fileName);
	if(sFileName.IsEmpty()) return S_OK;

	aplP21Header header;
	if(m_api->m_data.SaveP21(sFileName, header))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadFromFile(BSTR fileName, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	CString sFileName(fileName);

	if(sFileName.IsEmpty())
	{
		CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
			_T("Step Files (*.stp; *.std; *.txt)|*.stp; *.std; *.txt|All Files (*.*)|*.*||"));
		if(dlg.DoModal()==IDOK)	sFileName= dlg.GetPathName();		
	}

	if(sFileName.IsEmpty()) return S_OK;

	if(m_api->m_data.LoadFromFile(sFileName))
	{
		m_api->Init();
		result->boolVal= (short)0xffff;
	}	
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::SaveToFile(BSTR fileName, BOOL saveChanges, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	CString sFileName;
	
	bool bSaveChanges= false;
	if(saveChanges) bSaveChanges= true;
	
	if(m_api->m_data.SaveToFile(sFileName, bSaveChanges))
		result->boolVal= (short)0xffff;
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::RefreshRootCategories(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_categ_mgr.RefreshRootCategories())	
		result->boolVal= (short)0xffff;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetInstancesCharacteristic(IDispatch** longMap, long characteristic, long type, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	/*проверка*/
	IAplLongMap* pMap= NULL; 
	(*longMap)->QueryInterface(IID_IAplLongMap, (void**)&pMap);
	if(!pMap) return S_OK;//типа, нет такого интерфейса...
	pMap->Release();
	 
	try
	{
		CaplMap* map= reinterpret_cast<CAplLongMap*>(*longMap)->GetInnerMap();
		if(map)
		{
			if(m_api->m_charact_mgr.GetInstancesCharact(*map, 
					(CaplInstance*)characteristic,
					(CaplInstance*)type))
				
				result->boolVal= (short)0xffff;
		}	
	}
	catch(...)
	{
		
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SelectItem(VARIANT BaseClassifierSystems, long mode, BSTR sTitle, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= 0;	

	CaplInstance* classSystem= NULL;

	aplExtent baseSystems;
	LongArray arrayIn;
	CString strTitle(sTitle);
	
	GetVariant<LongArray, long>(BaseClassifierSystems, arrayIn);
	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		baseSystems.Add((CaplInstance*)arrayIn[i]);
	}

	if(m_api->m_classifier_mgr.SelectItem(&classSystem, baseSystems, (UINT)mode, strTitle))
		result->lVal= (long)classSystem;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateClassifierSystem(long ParentElement, BSTR sId, BSTR sName, BSTR sDescription, BOOL bTestUnique, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= 0;	

	CString strId(sId),
		strName(sName),
		strDscr(sDescription);

	bool bTest= false;
	if(bTestUnique) bTest= true;

	result->lVal= (long)m_api->m_classifier_mgr.CreateClassifierSystem((CaplInstance*)ParentElement,
		strId, strName, strDscr, bTest);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateClassifierLevel(long ClassifierSystem, long ParentElement, BSTR sId, BSTR sName, BSTR sDescription, BOOL bTestUnique, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= 0;	

	CString strId(sId),
		strName(sName),
		strDscr(sDescription);

	bool bTest= false;
	if(bTestUnique) bTest= true;

	result->lVal= (long)m_api->m_classifier_mgr.CreateClassifierLevel((CaplInstance*) ClassifierSystem,
		(CaplInstance*)ParentElement,
		strId, strName, strDscr,0, bTest);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteClassifierItem(long item, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_classifier_mgr.DeleteClassifierItem((CaplInstance*)item))	
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::ShowClassifierProperties(long item, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_classifier_mgr.ShowClassifierProperties((CaplInstance*)item))	
		result->boolVal= (short)0xffff;	

	return S_OK;
}


STDMETHODIMP CAplPssAPI::MoveClassifierSystem(long MovedSystem, long NewParent, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_classifier_mgr.MoveClassifierSystem((CaplInstance*)MovedSystem, (CaplInstance*)NewParent))	
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::MoveClassifierLevel(long MovedLevel, long NewParent, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_classifier_mgr.MoveClassifierLevel((CaplInstance*)MovedLevel, (CaplInstance*)NewParent))	
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetClassifierSystemBN(BSTR id, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= 0;	

	CString strId(id);
	result->lVal= (long)m_api->m_classifier_mgr.GetClassifierSystemBN(strId);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetClassifierSystemById(BSTR name, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= 0;	

	CString strName(name);
	result->lVal= (long)m_api->m_classifier_mgr.GetClassifierSystemById(strName);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetClassifierLevelByName(BSTR name, long ClassifierSystem, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= 0;	

	CString strName(name);
	result->lVal= (long)m_api->m_classifier_mgr.GetClassifierLevelByName(strName, (CaplInstance*) ClassifierSystem);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetClassifierLevelById(BSTR id, long ClassifierSystem, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= 0;	

	CString strId(id);
	result->lVal= (long)m_api->m_classifier_mgr.GetClassifierLevelById(strId, (CaplInstance*) ClassifierSystem);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetClassifierCharacteristic(long item, VARIANT *characteristics, BOOL bAllLevels, BOOL bCheckUnique, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; 
	result->boolVal= 0;


	aplExtent tempOutExt;
	LongArray outExt;

	bool check= false;
	if(bCheckUnique) check= true;

	bool allLevels= false;;
	if(bAllLevels) allLevels= true;

	if(m_api->m_classifier_mgr.GetClassifierCharacteristic((CaplInstance*)item, tempOutExt, allLevels, check))
	{
		result->boolVal= (short)0xffff;		
		
		for (int i= 0; i<tempOutExt.GetSize(); ++i)
		{
			outExt.Add((long)tempOutExt[i]);
		}
		FillVariant<LongArray, long>(characteristics, outExt, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetSubItems(VARIANT ClassifierLevels, VARIANT *items, VARIANT *rels, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent levels, ext, rel;
	LongArray outExt1, outExt2, outExt3;
	int i;
	
	GetVariant<LongArray, long>(ClassifierLevels, outExt3);
	for(i=0; i<outExt3.GetSize(); ++i)
	{
		levels.Add((CaplInstance*)outExt3[i]);
	}

	if(m_api->m_classifier_mgr.GetSubItems(levels, ext, &rel))
	{
		result->boolVal= (short)0xffff;		
		
		for (i= 0; i<ext.GetSize(); ++i)
		{
			outExt1.Add((long)ext[i]);
		}
		FillVariant<LongArray, long>(items, outExt1, VT_I4);
		
		for (i= 0; i<rel.GetSize(); ++i)
		{
			outExt2.Add((long)rel[i]);
		}
		FillVariant<LongArray, long>(rels, outExt2, VT_I4);
	}
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadSubClassifierSystems(long ClassifierSystem, VARIANT *SubElements, BOOL bAllLevels, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	bool allLevels= false;
	if(bAllLevels) allLevels= true;

	aplExtent items;
	LongArray outExt;

	if(m_api->m_classifier_mgr.LoadSubClassifierSystems((CaplInstance*) ClassifierSystem, items, allLevels))
	{
		result->boolVal= (short)0xffff;		
		
		for (int i= 0; i<items.GetSize(); ++i)
		{
			outExt.Add((long)items[i]);
		}
		FillVariant<LongArray, long>(SubElements, outExt, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadSubClassifierLevels(long ClassifierItem, VARIANT *SubElements, BOOL bAllLevels, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	bool allLevels= false;
	if(bAllLevels) allLevels= true;

	aplExtent items;
	LongArray outExt;

	if(m_api->m_classifier_mgr.LoadSubClassifierLevels((CaplInstance*) ClassifierItem, items, allLevels))
	{
		result->boolVal= (short)0xffff;		
		
		for (int i= 0; i<items.GetSize(); ++i)
		{
			outExt.Add((long)items[i]);
		}
		FillVariant<LongArray, long>(SubElements, outExt, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateClassifierAssociation(long item, long ClassifierLevel, BOOL bTestUnique, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= 0;	

	bool bTest= false;
	if(bTestUnique) bTest= true;

	result->lVal= (long)m_api->m_classifier_mgr.CreateClassifierAssociation((CaplInstance*) item, (CaplInstance*) ClassifierLevel, bTest);
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindClassifiersContained(long item, VARIANT *classifiers, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent items;
	LongArray outExt;

	if(m_api->m_classifier_mgr.FindClassifiersContained((CaplInstance*) item, items))
	{
		result->boolVal= (short)0xffff;		
		
		for (int i= 0; i<items.GetSize(); ++i)
		{
			outExt.Add((long)items[i]);
		}
		FillVariant<LongArray, long>(classifiers, outExt, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteClassifierAssociation(long item, long ClassifierLevel, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_classifier_mgr.DeleteClassifierAssociation((CaplInstance*) item, (CaplInstance*)ClassifierLevel))
	{
		result->boolVal= (short)0xffff;	
	}	

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadClassifierInfo(long Classifier, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_classifier_mgr.LoadClassifierInfo((CaplInstance*)Classifier))	
		result->boolVal= (short)0xffff;	

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadDictionary(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_classifier_mgr.LoadDictionary())	
		result->boolVal= (short)0xffff;	

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateWfProcess(BSTR sProcessId, BSTR sProcessName, BSTR sProcessDscr, 
										 long ProcessTmpl, long ProcessOwner, 
										 DATE StartDate, DATE FinishDate, DATE CheckDate, 
										 VARIANT TaskProt, VARIANT WorkObj, 
										 VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= 0;	

	CString sId(sProcessId), sName(sProcessName), sDscr(sProcessDscr);

	int i;
	aplExtent tskProt, wo;
	LongArray tmpArray;

	COleDateTime dt1(StartDate), dt2(FinishDate), dt3(CheckDate);
	CString date1, date2, date3;
	aplDate2String(dt1, date1);
	aplDate2String(dt2, date2);
	aplDate2String(dt3, date3);

	GetVariant<LongArray, long>(TaskProt, tmpArray);
	for(i= 0; i<tmpArray.GetSize(); i++)
	{
		tskProt.Add((CaplInstance*)tmpArray[i]);
	}
	
	tmpArray.RemoveAll();
	
	GetVariant<LongArray, long>(WorkObj, tmpArray);
	for(i= 0; i<tmpArray.GetSize(); i++)
	{
		wo.Add((CaplInstance*)tmpArray[i]);
	}

	result->lVal= (long)m_wf_mgr.CreateWfProcess(sId, sName, sDscr,
		(CaplInstance*)ProcessTmpl, (CaplInstance*)ProcessOwner, NULL, date1, date2, date3,
		tskProt, wo);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteWfProcess(long Process, BOOL SaveChanges, BOOL VerifyAccess, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	bool bVerify= true;
	if(!VerifyAccess)bVerify= false;
	bool bSave= true;
	if(!SaveChanges)bSave= false;
	
	CStringArray procLog;
	
	if(m_wf_mgr.DeleteWfProcess((CaplInstance*)Process, procLog, bSave, bVerify))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::RunWfProcess(long Process, BOOL VerifyAccess, long FirstActivity, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	bool bVerify= true;
	if(!VerifyAccess)bVerify= false;

	if(m_wf_mgr.RunWfProcess((CaplInstance*)Process, bVerify, (CaplInstance*)FirstActivity))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::RestartWfProcess(long Process, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= (long)m_wf_mgr.RestartWfProcess((CaplInstance*)Process);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SuspendWfProcess(long Process, BOOL VerifyAccess, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	bool bVerify= true;
	if(!VerifyAccess)bVerify= false;

	if(m_wf_mgr.SuspendWfProcess((CaplInstance*)Process, bVerify))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::TerminateWfProcess(long Process, BOOL VerifyAccess, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	bool bVerify= true;
	if(!VerifyAccess)bVerify= false;

	if(m_wf_mgr.TerminateWfProcess((CaplInstance*)Process, bVerify))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::EndWfProcess(long Process, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_wf_mgr.EndWfProcess((CaplInstance*)Process))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetUserTaskList(long Person, VARIANT *OutArray, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent ext;
	LongArray tmpArray;

	if(m_wf_mgr.GetUserTaskList((CaplInstance*)Person, ext))
	{
		result->boolVal= (short)0xffff;
		
		for(int i=0; i<ext.GetSize(); ++i)
			tmpArray.Add((long)ext[i]);		
		FillVariant<LongArray, long>(OutArray, tmpArray, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetUserProcessTempList(long Person, VARIANT *OutArray, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent ext;
	LongArray tmpArray;

	if(m_wf_mgr.GetUserProcessTempList((CaplInstance*)Person, ext))
	{
		result->boolVal= (short)0xffff;
		
		for(int i=0; i<ext.GetSize(); ++i)
			tmpArray.Add((long)ext[i]);		
		FillVariant<LongArray, long>(OutArray, tmpArray, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetUserProcessList(long Person, VARIANT *OutArray, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent ext;
	LongArray tmpArray;

	if(m_wf_mgr.GetUserProcessList((CaplInstance*)Person, ext))
	{
		result->boolVal= (short)0xffff;
		
		for(int i=0; i<ext.GetSize(); ++i)
			tmpArray.Add((long)ext[i]);		
		FillVariant<LongArray, long>(OutArray, tmpArray, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetProcessTasks(long Process, VARIANT *OutArray, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent ext;
	LongArray tmpArray;

	if(m_wf_mgr.GetProcessTasks((CaplInstance*)Process, ext))
	{
		result->boolVal= (short)0xffff;
		
		for(int i=0; i<ext.GetSize(); ++i)
			tmpArray.Add((long)ext[i]);		
		FillVariant<LongArray, long>(OutArray, tmpArray, VT_I4);
	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadProcessInfo(long Process, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_wf_mgr.LoadProcessInfo((CaplInstance*)Process))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::ShowProcessProperties(long Process, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_wf_mgr.ShowProcessProperties((CaplInstance*)Process))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::RestartTask(long Task, long NewManager, long NewPerformer, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= (long)m_wf_mgr.RestartTask((CaplInstance*)Task, (CaplInstance*)NewManager, (CaplInstance*)NewPerformer);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::RunTask(long Task, BOOL VerifyAccess, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	bool bVerify= true;
	if(!VerifyAccess)bVerify= false;

	if(m_wf_mgr.RunTask((CaplInstance*)Task, bVerify))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateTask(long Process, long Activity, VARIANT SubProcesses, BSTR sTaskId, BSTR sTaskName, BSTR sTaskDscr, DATE StartDate, DATE FinishDate, DATE CheckDate, long Manager, long Performer, long PreviousTask, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;
	result->lVal= 0;	

	CString sId(sTaskId), sName(sTaskName), sDscr(sTaskDscr);
	aplExtent ext;
	LongArray tmpArray;

	COleDateTime dt1(StartDate), dt2(FinishDate), dt3(CheckDate);
	CString date1, date2, date3;
	aplDate2String(dt1, date1);
	aplDate2String(dt2, date2);
	aplDate2String(dt3, date3);

	GetVariant<LongArray, long>(SubProcesses, tmpArray);
	for(int i= 0; i<tmpArray.GetSize(); i++)
	{
		ext.Add((CaplInstance*)tmpArray[i]);
	}

	result->lVal= (long)m_wf_mgr.CreateTask((CaplInstance*)Process, (CaplInstance*)Activity,0,
		ext, (CaplInstance*)PreviousTask, _T("medium"), 
		sId, sName, sDscr, (CaplInstance*)Performer, (CaplInstance*)Manager,
		date1, date2, date3);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SuspendTask(long Task, BOOL VerifyAccess, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	bool bVerify= true;
	if(!VerifyAccess)bVerify= false;

	if(m_wf_mgr.SuspendTask((CaplInstance*)Task, bVerify))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::EndTask(long Task, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_wf_mgr.EndTask((CaplInstance*)Task))
		result->boolVal= (short)0xffff;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadTaskInfo(long Task, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_wf_mgr.LoadTaskInfo((CaplInstance*)Task))
		result->boolVal= (short)0xffff;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::ShowTaskProperties(long Task, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_wf_mgr.ShowTaskProperties((CaplInstance*)Task))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetProcessComponents(long ProcessOrTmpl, VARIANT *OutArray, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent ext;
	LongArray tmpArray;

	if(m_wf_mgr.GetProcessComponents((CaplInstance*)ProcessOrTmpl, ext))
	{
		result->boolVal= (short)0xffff;
		
		for(int i=0; i<ext.GetSize(); ++i)
			tmpArray.Add((long)ext[i]);		
		FillVariant<LongArray, long>(OutArray, tmpArray, VT_I4);
	}
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetProcessTmplById(BSTR sTmplId, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString sId(sTmplId);

	result->vt=VT_I4;
	result->lVal= (long)m_wf_mgr.GetProcessTmplById(sId);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadTemplates(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_wf_mgr.LoadTemplates())
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetConnectors(long TaskOrActivity, VARIANT *IncomConnectors, VARIANT *OutcomConnectors, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	aplExtent ext1, ext2;
	LongArray tmpArray;

	if(m_wf_mgr.GetConnectors((CaplInstance*)TaskOrActivity, ext1, ext2))
	{
		result->boolVal= (short)0xffff;
		int i;
		for(i=0; i<ext1.GetSize(); ++i)
			tmpArray.Add((long)ext1[i]);		
		FillVariant<LongArray, long>(IncomConnectors, tmpArray, VT_I4);

		tmpArray.RemoveAll();

		for(i=0; i<ext2.GetSize(); ++i)
			tmpArray.Add((long)ext2[i]);		
		FillVariant<LongArray, long>(OutcomConnectors, tmpArray, VT_I4);

	}
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetCurrentUser(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4; 
	result->lVal= (long)m_api->m_data.GetCurrUser();

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetNameCurrUser(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
		result->vt=VT_BSTR; 

	CString sName= m_api->m_data.GetNameCurrUser();
	if(!sName.IsEmpty())
	{
#ifdef _UNICODE
		result->bstrVal= W2BSTR(LPCWSTR(sName));
#else
		result->bstrVal= A2BSTR(LPCSTR(sName));
#endif
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetNameCurrConnection(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
		result->vt=VT_BSTR; 

	CString sName= m_api->m_data.GetNameCurrConnection();;
	if(!sName.IsEmpty())
	{
#ifdef _UNICODE
		result->bstrVal= W2BSTR(LPCWSTR(sName));
#else
		result->bstrVal= A2BSTR(LPCSTR(sName));
#endif
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::IsAdmin(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_appr_mgr.IsAdmin())
		result->boolVal= (short)0xffff;		

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetInstanceAccessmode(long instance, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;result->lVal= 0;

	if(!instance) return S_OK;

	result->lVal= ((CaplInstance*)instance)->GetAccessmode();	

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateEnumirationCharacteristic(long item, long characteristic, long type, BSTR value, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!characteristic || !item) return S_OK;
	
	result->vt=VT_I4;
	result->lVal= 0;	
	
	CString sValue(value);

	CaplInstance* val= m_api->m_data.CreateInstance(m_api->m_charact_mgr.e_enum_value);
	if(val)
	{
		m_api->m_data.PutAttr(val, m_api->m_charact_mgr.a_apl_charact_val_enum_val, sValue);
		m_api->m_data.PutAttr(val, m_api->m_charact_mgr.a_apl_charact_val_item, (CaplInstance*)item);
		m_api->m_data.PutAttr(val, m_api->m_charact_mgr.a_apl_charact_val_type, (CaplInstance*)type);
		m_api->m_data.PutAttr(val, m_api->m_charact_mgr.a_apl_charact_val_charact, (CaplInstance*)characteristic);	
		bool bOldFlag= m_api->m_charact_mgr.m_AutoSave;
		m_api->m_charact_mgr.m_AutoSave= false;
		CaplInstance* val_ver= m_api->m_charact_mgr.CreateCharValVersion(val, _T("0"));		
		m_api->m_charact_mgr.m_AutoSave= bOldFlag;
		//m_api->SaveChanges(); какого #%* здесь стоит SaveChanges! Он вызывается из менеджера и только при флаге AutoSave!
		
		result->lVal= (long)val;
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetInstanceName(long instance, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BSTR;
	
	if(!instance) return S_OK;

	CString sName;
	m_api->GetItemName((CaplInstance*)instance, sName);
	
	if(!sName.IsEmpty())
	{
#ifdef _UNICODE
		result->bstrVal= W2BSTR(LPCWSTR(sName));	
#else
		result->bstrVal= A2BSTR(LPCSTR(sName));	
#endif
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SaveBlobBN(long instance, BSTR attr, BSTR filePath, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	CString sAttrName(attr);
	CString sFileName(filePath);
	long iCode;

	LPTSTR szBuf= sFileName.GetBuffer(sFileName.GetLength()+1);

	if(m_api->m_data.NET_SaveBlobBN((CaplInstance*)instance, sAttrName, szBuf, iCode))
		result->boolVal= (short)0xffff;

	sFileName.ReleaseBuffer();
	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteBlobBN(long instance, BSTR attr, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	CString sAttrName(attr);
	
	if(m_api->m_data.NET_DeleteBlobBN((CaplInstance*)instance, sAttrName))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadBlobBN(long istance, BSTR attr, BSTR fileName, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	CString sAttrName(attr);
	CString sFilePath(fileName);

	if(m_api->m_data.NET_LoadBlobBN((CaplInstance*)istance, sAttrName, sFilePath))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetBlobSizeBN(long instance, BSTR attr, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;result->lVal= 0;
	
	CString sAttrName(attr);

	long iRes;
	CaplAttr* pAttr= m_api->m_data.GetAttrDefinition(((CaplInstance*)instance)->GetType(), sAttrName);
	if(m_api->m_data.NET_GetBlobSize((CaplInstance*)instance, pAttr, iRes))
		result->lVal= iRes;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CopyGroupeAccess(long pattern, VARIANT destination, BSTR sWaitText, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	LongArray tmpArray;
	CString sText(sWaitText);
	if(sText.IsEmpty()) sText= APL_T("Установка доступа...");

	aplExtent ext;
	GetVariant<LongArray, long>(destination, tmpArray);
	for(int i= 0; i<tmpArray.GetSize(); i++)
	{
		ext.Add((CaplInstance*)tmpArray[i]);
	}
	
	if(m_api->m_data.NET_CopyGroupeAccess((CaplInstance*)pattern, ext, sText))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SetCheckCurAccess(BOOL bBefoSetAccess, BOOL bAfterSetAccess, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	bool bBefor, bAfter;

	(bBefoSetAccess==TRUE)?bBefor= true:bBefor= false;
	(bAfterSetAccess==TRUE)?bAfter= true:bAfter= false;

	m_api->m_data.SetCheckCurAccess(bBefor, bAfter);
	result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::FreeInstancesAttr(VARIANT instances, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())	
	result->vt=VT_BOOL; result->boolVal= 0;

	LongArray tmpArray;
	aplExtent ext;

	GetVariant<LongArray, long>(instances, tmpArray);
	for(int i= 0; i<tmpArray.GetSize(); i++)
	{
		ext.Add((CaplInstance*)tmpArray[i]);
	}
	
	m_api->m_data.FreeInstancesAttr(ext);
	result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::ClearInstances(VARIANT instances, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	LongArray tmpArray;
	aplExtent ext;

	GetVariant<LongArray, long>(instances, tmpArray);
	for(int i= 0; i<tmpArray.GetSize(); i++)
	{
		ext.Add((CaplInstance*)tmpArray[i]);
	}
	
	if(m_api->m_data.ClearInstances(ext))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SetMaxItemsLoad(LONG MaxItemsLoad, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	m_api->SetMaxItemsLoad(MaxItemsLoad);
	result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CopyAccessFromInst2Inst(VARIANT patterns, VARIANT destinations, BSTR sWaitText, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	LongArray tmpArray;
	CString sText(sWaitText);
	if(sText.IsEmpty()) sText= APL_T("Установка доступа...");

	int i;
	aplExtent ext1, ext2;
	GetVariant<LongArray, long>(patterns, tmpArray);
	for(i= 0; i<tmpArray.GetSize(); i++)
	{
		ext1.Add((CaplInstance*)tmpArray[i]);
	}
	tmpArray.RemoveAll();
	
	GetVariant<LongArray, long>(destinations, tmpArray);
	for(i= 0; i<tmpArray.GetSize(); i++)
	{
		ext2.Add((CaplInstance*)tmpArray[i]);
	}
	
	if(m_api->m_data.NET_CopyAccessFromInst2Inst(ext1, ext2, sText))
		result->boolVal= (short)0xffff;		

	return S_OK;
}

STDMETHODIMP CAplPssAPI::put_SetHideMode(BOOL newVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	if(newVal) m_api->m_data.SetHideMode(true);
	else m_api->m_data.SetHideMode(false);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadProductDictionary(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_categ_mgr.LoadContextInfo() && m_api->m_prd_mgr.LoadAssortment())
		result->boolVal= (short)0xffff;		

	return S_OK;
}

STDMETHODIMP CAplPssAPI::IsVersionOK(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(m_api->m_data.IsVersionOk())
		result->boolVal= (short)0xffff;		

	return S_OK;
}

STDMETHODIMP CAplPssAPI::StartAdministrationMode(BSTR Admin,  BSTR Password,  VARIANT* result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	CString sUser(Admin);
	CString sPassword(Password);

	if(m_api->m_data.NET_StartAdminMode(sUser, sPassword))
		result->boolVal= (short)0xffff;	
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::EndAdministrationMode(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	if(m_api->m_data.NET_ExitAdminMode())
		result->boolVal= (short)0xffff;			

	return S_OK;
}

STDMETHODIMP CAplPssAPI::get_AdminMode(BOOL *pVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	*pVal= (m_api->m_data.GetAdminMode())?TRUE:FALSE;
	
	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetAccessString(long instance, BOOL bForUI, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BSTR;
	
	CaplInstance* inst= (CaplInstance*)instance;
	if(!inst || !m_api->m_data.IsMyInstance(inst, true)) return S_OK;

	CString sAccessStr;
	bool for_user= true;
	if(!bForUI)for_user= false;
	
	if(m_api->m_data.NET_GetExtentAccess2String(inst, sAccessStr, for_user))
	{
#ifdef _UNICODE
		result->bstrVal= W2BSTR(LPCWSTR(sAccessStr));
#else
		result->bstrVal= A2BSTR(LPCSTR(sAccessStr));
#endif
	}

	return S_OK;
}


STDMETHODIMP CAplPssAPI::GetInstanceSysInfo(long instance, BSTR *createdBy, DATE* createTime,  
											BSTR *editedBy, DATE *editTime, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	CaplInstance* inst= (CaplInstance*)instance;
	if(!m_api->m_data.IsMyInstance(inst, true))
		return S_OK;

	CaplTAggr<SInstInfo*,SInstInfo*,APLAGGR_AUTOKILLREF> data;
	SInstInfo* infoStruct= NULL;
	CString sStr;
	
	infoStruct= new SInstInfo(inst);
	data.Add(infoStruct);

	if(!m_api->m_data.NET_LoadInstUserDataTimeInfo(data))
		return S_OK;

	if(infoStruct->create_user)
	{
		m_api->m_data.GetAttr(infoStruct->create_user, m_api->m_appr_mgr.a_apl_user_name, sStr);
#ifdef _UNICODE
		*createdBy= W2BSTR(LPCWSTR(sStr));
#else
		*createdBy= A2BSTR(LPCSTR(sStr));
#endif
	}

	if(infoStruct->create_date)
	{
		*createTime= infoStruct->create_date;
	}

	if(infoStruct->update_user)
	{
		m_api->m_data.GetAttr(infoStruct->update_user, m_api->m_appr_mgr.a_apl_user_name, sStr);
#ifdef _UNICODE
		*editedBy= W2BSTR(LPCWSTR(sStr));
#else
		*editedBy= A2BSTR(LPCSTR(sStr));
#endif
	}

	if(infoStruct->update_date)
	{
		*editTime= infoStruct->update_date;
	}
	
	result->boolVal= (short)0xffff;
	return S_OK;
}

STDMETHODIMP CAplPssAPI::EndTask2(long Task, long Connector, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(!m_api->m_data.IsMyInstance((CaplInstance*)Task, true))
		return S_OK;
	if(!m_api->m_data.IsMyInstance((CaplInstance*)Connector, true))
		return S_OK;

	if(m_wf_mgr.EndTask((CaplInstance*)Task, (CaplInstance*)Connector))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadOptionDictionary(VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	if(m_api->m_options_mgr.LoadDictionary())
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateStringOption(BSTR Name, BSTR Value, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;result->lVal= 0;

	CString sName(Name);
	CString sValue(Value);

	result->lVal= (long)m_api->m_options_mgr.CreateOption(sName, sValue);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateNumericOption(BSTR Name, long Value, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;result->lVal= 0;

	CString sName(Name);
	
	result->lVal= (long)m_api->m_options_mgr.CreateOption(sName, Value);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateInstanceOption(BSTR Name, long Value, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;result->lVal= 0;

	if(!m_api->m_data.IsMyInstance((CaplInstance*)Value, true))
		return S_OK;

	CString sName(Name);
	
	result->lVal= (long)m_api->m_options_mgr.CreateOption(sName, (CaplInstance*)Value);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::DeleteOption(long Option, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	if(!m_api->m_data.IsMyInstance((CaplInstance*)Option, true))
		return S_OK;

	if(((CaplInstance*)Option)->GetType()!=m_api->m_options_mgr.e_inst &&
		((CaplInstance*)Option)->GetType()!=m_api->m_options_mgr.e_str &&
		((CaplInstance*)Option)->GetType()!=m_api->m_options_mgr.e_int)
		return S_OK;

	if(m_api->m_options_mgr.DeleteOption((CaplInstance*)Option))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::FindOption(BSTR Option, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;result->lVal= 0;
	
	CString sName(Option);
	result->lVal= (long)m_api->m_options_mgr.FindOptionBN(sName);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::CreateOption(BSTR Name, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;result->lVal= 0;

	CString sName(Name);
	
	result->lVal= (long)m_api->m_options_mgr.CreateOption(sName);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetStringOption(BSTR Name, BSTR DefaultValue, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())

	CString sName(Name);
	CString sDefVal(DefaultValue);
	CString sValue;

	m_api->m_options_mgr.GetOptionValueBN(sName, sValue, sDefVal);

	result->vt=VT_BSTR;
#ifdef _UNICODE
	result->bstrVal= W2BSTR(LPCWSTR(sValue));
#else
	result->bstrVal= A2BSTR(LPCSTR(sValue));
#endif

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetNumbericOption(BSTR Name, long DefaultValue, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;result->lVal= -1;
	
	CString sName(Name);
	result->lVal= m_api->m_options_mgr.GetIntOptionValueBN(sName, DefaultValue);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::GetInstanceOption(BSTR Name, long DefaultValue, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4;result->lVal= 0;
	
	if(!m_api->m_data.IsMyInstance((CaplInstance*)DefaultValue, true))
		return S_OK;

	CString sName(Name);
	result->lVal= (long)m_api->m_options_mgr.GetInstOptionValueBN(sName, (CaplInstance*)DefaultValue);

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadOptionsInfo(long Option, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;
	
	if(!m_api->m_data.IsMyInstance((CaplInstance*)Option, true))
		return S_OK;

	if(m_api->m_options_mgr.LoadOptionsInfo((CaplInstance*)Option))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SetSignMode(long lMode, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_I4; result->lVal= -1;

	/*enum ESignMode {APL_SIMPLE_MODE, APL_QUICK_MODE_WITH_DLG, APL_QUICK_MODE_WITHOUT_DLG};*/
	ESignMode smIn, smOut;

	switch (lMode)
	{
		case 0: smIn= APL_SIMPLE_MODE; break;
		case 1: smIn= APL_QUICK_MODE_WITH_DLG; break; 
		case 2: smIn= APL_QUICK_MODE_WITHOUT_DLG; break; 
		default:return S_OK;
	}

	smOut= m_api->m_appr_mgr.SeSignModeForCryptMgr(smIn,true);

	switch (smOut)
	{
		case APL_SIMPLE_MODE:result->lVal=0;break;
		case APL_QUICK_MODE_WITH_DLG:result->lVal=1;break;
		case APL_QUICK_MODE_WITHOUT_DLG:result->lVal=2;break;
		default:return S_OK;
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SelectPersonsOrganizations2(long mode, BSTR sDialogTitle, BSTR sTreeTitle, VARIANT rootObjects, VARIANT *persOrOrgs, BOOL bShowUserWG, BOOL bRecursiveSelect, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	result->vt=VT_BOOL; result->boolVal= 0;
	
	LongArray tempArray;

	bool bShowWG= true;
	if(!bShowUserWG) bShowWG= false;

	bool bTraverse= true;
	if(!bRecursiveSelect) bTraverse= false;
	
	CString sTitle(sDialogTitle), sTrTitle(sTreeTitle);

	aplExtent rootExt;	
	LongArray arrayIn;
	
	GetVariant<LongArray, long>(rootObjects, arrayIn);
	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		rootExt.Add((CaplInstance*)arrayIn[i]);
	}
	
	aplExtent * rootExtIn= NULL;
	aplExtent ext;
	if(rootExt.GetSize()) rootExtIn= &rootExt;

	if(m_api->m_appr_mgr.SelectPersonsOrganizations(mode, ext, bShowWG, 
		bTraverse, sTitle, sTrTitle, rootExtIn))
	{
		result->boolVal= (short)0xffff;		
		for(int i= 0; i<ext.GetSize(); i++)
		{
			tempArray.Add((long)ext[i]);
		}
		FillVariant<LongArray, long>(persOrOrgs, tempArray, VT_I4);
	}

	return S_OK;
}

STDMETHODIMP CAplPssAPI::SelectPersonOrOrganization2(long mode, BSTR sDialogTitle, BSTR sTreeTitle, VARIANT rootObjects, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	if(!m_api || !apidata.IsConnected()) return S_OK;

	CString sTitle(sDialogTitle), sTrTitle(sTreeTitle);
	
	aplExtent rootExt;	
	LongArray arrayIn;
	
	GetVariant<LongArray, long>(rootObjects, arrayIn);
	for(int i=0; i<arrayIn.GetSize(); ++i)
	{
		rootExt.Add((CaplInstance*)arrayIn[i]);
	}	

	result->vt= VT_I4;
	result->lVal= (long)m_api->m_appr_mgr.SelectPersonOrOrganization(mode, rootExt, sTitle, sTrTitle);
	return S_OK;
}

STDMETHODIMP CAplPssAPI::SetLoadCharacteristicValues(BOOL NewValue, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	bool bNewValue= (TRUE==NewValue)?true:false;

	if(m_api->SetLoadCharacteristicValues(bNewValue))
		result->boolVal= (short)0xffff;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::get_LoadCharacteristicValues(BOOL *pVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	*pVal= (true==m_api->m_load_characteristic_values)?TRUE:FALSE;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::put_LoadCharacteristicValues(BOOL newVal)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	
	m_api->m_load_characteristic_values= (TRUE==newVal)?true:false;

	return S_OK;
}

STDMETHODIMP CAplPssAPI::LoadDataModule(BSTR DMCode, BSTR pictureRef, BSTR path, BSTR* file, VARIANT *result)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState())
	result->vt=VT_BOOL; result->boolVal= 0;

	CString sDMCode (DMCode);
	CString sPath (path);
	CString sPictureRef (pictureRef);
	CString sFileName;
	CString fname;
	CString buf;
	CFileFind ff;


	if(sPath==_T(""))  aplGetTempPath(sPath);
	if(sPath[sPath.GetLength()-1] !=_T('\\')) sPath+=_T('\\');

	CaplInstance *doc=m_api->m_doc_mgr.FindDocById(sDMCode);
	if(doc==0)
	{
		sFileName=APL_T("Модуль данных не найден!");
#ifdef _UNICODE
		*file= W2BSTR(LPCWSTR(sFileName));
#else
		*file= A2BSTR(LPCSTR(sFileName));
#endif
		//AfxMessageBox(APL_T("Модуль данных не найден!"));
		return S_OK;

	}

	if(sPictureRef==_T(""))
	{
		// Читаем сам модуль данных
		m_api->m_doc_mgr.GetFileName(doc,fname);
		sFileName=sPath+fname;
		if(TRUE==ff.FindFile(sFileName,0)) CFile::Remove(sFileName);
		if(!m_api->m_doc_mgr.LoadRevision(doc,sFileName,false,false))
		{
			sFileName=APL_T("Не удалось сохранить файл на диск!");
			//AfxMessageBox(sFileName);
#ifdef _UNICODE
			*file= W2BSTR(LPCWSTR(sFileName));
#else
			*file= A2BSTR(LPCSTR(sFileName));
#endif
		}
		else result->boolVal= (short)0xffff;			
		
#ifdef _UNICODE
		*file= W2BSTR(LPCWSTR(sFileName));
#else
		*file= A2BSTR(LPCSTR(sFileName));
#endif
		return S_OK;
	}

	
	// Читаем картинку модуля данных
	CaplInstance *rev;
	m_api->m_data.GetAttr(doc,m_api->m_doc_mgr.a_apl_doc_active,rev);
	if(rev!=0)
	{
		aplExtent pictures;
		m_api->m_data.GetAttr(rev,m_api->m_doc_mgr.a_apl_doc_rev_pictures,pictures);
		int i;
		for(i=0;i<pictures.GetSize();i++)
		{
			m_api->m_data.GetAttr(pictures[i],m_api->m_doc_mgr.a_apl_stored_document_code,buf);
			
			if(0==sPictureRef.CompareNoCase(buf))
			{
				m_api->m_data.GetAttr(pictures[i],m_api->m_doc_mgr.a_apl_stored_document_file_name,buf);
				int j=buf.ReverseFind(_T('\\'));
				if(j>0) fname=buf.Right(buf.GetLength()-j-1);
				else fname=buf;

				sFileName=sPath+fname;
				
				if(TRUE==ff.FindFile(sFileName,0)) CFile::Remove(sFileName);
				if (m_api->m_data.NET_LoadBlob(pictures[i], m_api->m_doc_mgr.a_apl_stored_document_source, sFileName))
				result->boolVal= (short)0xffff;
				else 
				{	sFileName=APL_T("Не удалось сохранить файл на диск!");
					//AfxMessageBox(sFileName);
				}
#ifdef _UNICODE
				*file= W2BSTR(LPCWSTR(sFileName));
#else
				*file= A2BSTR(LPCSTR(sFileName));
#endif
				return S_OK;
			}
	
		}
	}

	sFileName=APL_T("Иллюстрация модуля данных не найдена!");
	//AfxMessageBox(sFileName);
#ifdef _UNICODE
	*file= W2BSTR(LPCWSTR(sFileName));
#else
	*file= A2BSTR(LPCSTR(sFileName));
#endif
	return S_OK;
}
