
// RunPlugin.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "RunPlugin.h"
#include "RunPluginDlg.h"

#include <apl_gui.h>
#include <apl_api.h>
#include <aplProjectMgr.h>
//#include <aplWorkFlowManager.h>


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


typedef bool (*LPFUNCTION)(CaplAPI*, aplExtent&, bool);

// CRunPluginApp

BEGIN_MESSAGE_MAP(CRunPluginApp, CWinApp)
	ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()


// CRunPluginApp construction

CRunPluginApp::CRunPluginApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}


// The one and only CRunPluginApp object

CRunPluginApp theApp;


// CRunPluginApp initialization

BOOL CRunPluginApp::InitInstance()
{
	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization
	SetRegistryKey(_T("Local AppWizard-Generated Applications"));

	//Многоязычность интерфейса
	CaplTranslate::SetCurLocaleFromReg(); 


	// берем параметры
	CString params=m_lpCmdLine,buf;
	CStringArray p;
	int i=-1;
	bool isStr=false;
	while(1)
	{
		i++;
		TCHAR c=params[i];
		if(c==_T('\0')) break;
		if(c==_T('\"')) {isStr=!isStr; continue;}
		else if(c==_T(' '))
		{
			if(!isStr)
			{
				if(buf!=_T(""))
				{
					p.Add(buf);
					buf=_T("");
				}
				continue;
			}
		}
		buf+=c;
	}
	if(buf!=_T(""))p.Add(buf);

	if(p.GetSize()<2)
	{
		CRunPluginDlg dlg;
		dlg.DoModal();
		return FALSE;
	}

	HMODULE hMod = AfxLoadLibrary(p[0]);
	if(hMod==0)
	{
		buf.Format(APL_T("Ошибка при загрузке модуля '%s'!"),LPCTSTR(p[0]));
		AfxMessageBox(buf);
		return FALSE;
	}

	LPFUNCTION lpFunc;
#ifdef _UNICODE
	CaplStringAdapter sP1Adapter(p[1]);
	(FARPROC&)lpFunc = GetProcAddress(hMod,(LPCSTR)sP1Adapter);
#else
	(FARPROC&)lpFunc = GetProcAddress(hMod,LPCSTR(p[1]));
#endif
	if(lpFunc==0)
	{
		buf.Format(APL_T("Ошибка при загрузке функции '%s'!"),LPCTSTR(p[1]));
		AfxMessageBox(buf);
		AfxFreeLibrary(hMod);
		return FALSE;
	}


	CString user,psw, connect;
	if(p.GetSize()>3) user=p[3];
	if(p.GetSize()>4) psw=p[4];
	if(p.GetSize()>5) connect=p[5];


	CaplAPI m_api;
	//CaplWorkFlowManager		m_wf_mgr;
	//m_api.m_wf_mgr= &m_wf_mgr;
	CaplProjectManager *m_project_mgr= new CaplProjectManager;
	if(m_api.m_project_mgr) delete m_api.m_project_mgr;
	m_api.m_project_mgr= m_project_mgr;

	if(!m_api.Connect(LPCTSTR(user),LPCTSTR(psw),LPCTSTR(connect))) return FALSE;


	//m_wf_mgr.Attach(&m_api);

	m_api.m_appr_mgr.LoadOrgStruct();
	m_api.m_charact_mgr.LoadDictionary();
	m_api.m_unit_exch_mgr.InitUnitsBases();
	m_api.m_charact_mgr.LoadContextInfo();
	m_api.m_prd_mgr.LoadDictionary();
	m_api.m_bp_mgr.LoadDictionary();
	m_api.m_doc_mgr.LoadDictionary();
	m_api.m_project_mgr->LoadDictionary();
	m_api.m_options_mgr.LoadDictionary();
	
	// Чтение текущего User-a
	CaplLoadData ld(&m_api.m_data,DEF_SOURCE);
	CaplInstance *inst=m_api.m_data.GetCurrUser();
	if(inst!=0)
	{
		CaplAttr *attr=m_api.m_appr_mgr.a_apl_user_po;
		ld.AddQuery(_T('i'), inst->GetId(), 0,attr, true);
		if (!ld.LoadEx())AfxMessageBox(APL_T("Ошибка чтения данных о пользователе!"),MB_OK|MB_ICONSTOP);
		ld.ClearQuery();
	}

	bool bRunFunct=true;
	inst=0;
	if(p.GetSize()>2)
	{
		if(p[2]!=_T(""))
		{
			if((p[2])[0]!=_T('#')) AfxMessageBox(APL_T("Неверное задание ID объекта")); 
			else
			{
				inst=m_api.m_data.GetInstById(_atoi(LPCTSTR(p[2])+1));
				if(inst==0) {AfxMessageBox(APL_T("Объект не найден!")); bRunFunct=false;}
			}
		}
	}

	aplExtent items;
	if(inst!=0) items.Add(inst);
	if(bRunFunct) lpFunc(&m_api, items, false);
	m_api.Disconnect();
	AfxFreeLibrary(hMod);
	return FALSE;
}
