// RunPython.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include "RunPython.h"
#include "ScriptExecutor.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 唯一的应用程序对象

CWinApp theApp;

using namespace std;

BOOL Python27Dir(LPTSTR lpPython27Dir, int nBufferLen);

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// 初始化 MFC 并在失败时显示错误
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: 更改错误代码以符合您的需要
		_tprintf(_T("错误: MFC 初始化失败\n"));
		nRetCode = 1;
	}
	else
	{
		while(true)
		{
			// TODO: 在此处为应用程序的行为编写代码。
			CScriptExecutor excutor;
			excutor.InitScript(
				//"E:\\bin\\ScbcCopyKey\\ScbcTest.py", 
				"D:\\SAT\\runner\\btc_runner_se\\runner\\output\\ODF_NPI_RT2841\\20191119172310094\\192.168.1.119_5555\\cases\\RT_2841\\ODF_NPI_RT2841\\picture\\22.py",
				"D:\\SAT\\log.txt", 
				"",
				SUBPROCESS);
			excutor.StartScript();

			Sleep(500);
			while( !excutor.IsScriptOver() )
				Sleep(100);

			Sleep(2000);
			OutputDebugString("--------------------------------------\n");
		}

	}

	system("pause");

	return nRetCode;
}

// 全局变量;
std::vector<CScriptExecutor*> g_vtScriptExcutor;

RUNPYTHON_API DWORD RunPyScript(LPCTSTR lpScriptFile, LPCTSTR lpExtraSentence, LPCTSTR lpScriptLog, BOOL bSubProcess)
{
	CScriptExecutor *pExcutor = new CScriptExecutor();
	if ( pExcutor )
	{
		// 初始化脚本;
		pExcutor->InitScript(lpScriptFile, lpScriptLog, lpExtraSentence, bSubProcess ? SUBPROCESS : EMBEDDED);
		// 执行脚本;
		if ( !pExcutor->StartScript() )
		{
			delete pExcutor;
			pExcutor = NULL;
			return -1;
		}

		// 压入全局变量;
		g_vtScriptExcutor.push_back(pExcutor);

		// 返回脚本Id;
		return pExcutor->GetScriptId();
	}

	return -1;
}

RUNPYTHON_API bool StopPyScript(DWORD dwScriptId, BOOL bSubProcess)
{
	bool ret = false;
	CScriptExecutor *pExcutor = NULL;
	std::vector<CScriptExecutor*>::iterator it = g_vtScriptExcutor.begin();
	for ( ; it != g_vtScriptExcutor.end(); it++ )
	{
		pExcutor = *it;
		if ( pExcutor->GetScriptId() == dwScriptId )
		{
			ret = true;
			pExcutor->StopScript();
			break;
		}
	}

	return ret;
}

RUNPYTHON_API bool IsPyScriptOver(DWORD dwScriptId, BOOL bSubProcess)
{
	bool ret = false;
	CScriptExecutor *pExcutor = NULL;
	std::vector<CScriptExecutor*>::iterator it = g_vtScriptExcutor.begin();
	for ( ; it != g_vtScriptExcutor.end(); it++ )
	{
		pExcutor = *it;
		if ( pExcutor->GetScriptId() == dwScriptId )
		{
			if ( ret = pExcutor->IsScriptOver() )
			{
				break;
			}		
		}
	}

	return ret;
}

RUNPYTHON_API void CleanPyScript(DWORD dwScriptId)
{
	CScriptExecutor *pExcutor = NULL;
	std::vector<CScriptExecutor*>::iterator it = g_vtScriptExcutor.begin();
	for ( ; it != g_vtScriptExcutor.end(); it++ )
	{
		pExcutor = *it;
		if ( pExcutor->GetScriptId() == dwScriptId )
		{
			// 先停止脚本;
			pExcutor->StopScript();

			// 再清除;
			delete pExcutor;
			pExcutor = NULL;
			g_vtScriptExcutor.erase(it);
			break;
		}
	}
}