/*<<<***************************************************************************
The MIT License (MIT)

Copyright(C) 2013 - 2015 Marc Mirti Mancinelli, Christophe Lardau and Philippe Pamart (xdcube.org)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
#Title: xbApp
#Project: xdcBase
////////////////////////////////////////////////////////////////////////////////
#Author: Marc MIRTI MANCINELLI
#History:
<15/09/2013: creation.
12/02/2014: this notice inserted.
***************************************************************************>>>*/
#include "stdafx.h"

#include "xbApp.h"
#include "xbVersion.h"

extern volatile bool		g_bFirstOutput;
extern volatile DWORD		g_cChg;
void	xbAppBase::ThreadContextRelease()
{
}

bool xbAppBase::onThreadShouldStop( ulong evMask ) const
{
	return (evMask & (xbTHREADEVENT_KILL|xbTHREADEVENT_STOP|xbTHREADEVENT_STOPTASK))?true:false;
}

bool	xbAppBase::onThreadMsg(MSG *pMsg,bool *pbQuit)
{
	return false;
}

void xbAppBase::checkStop() const
{
	if (!shouldStop())
		return;
	xbThrow xbEuser(E_ABORT,"Operation cancelled");
}
void xbAppBase::checkStop(const xbString &oplabel) const
{
	if (!shouldStop())
		return;
	xbThrow xbEuser(E_ABORT,oplabel+" cancelled");
}

BOOL __stdcall BreakHandlerRoutine(DWORD dwCtrlType)
{
	xbRdbgOutput(xbGetProductName() + "/BreakHandlerRoutine() receiving signal "+xbString(dwCtrlType)+"...");
	bool bRet = false;
	eProtectBegin();

	xbAppConsole *pAppConsole;
	xbCastInReq((xbBase*)xbAppBase::Appli(),&pAppConsole);
	pAppConsole->onBreakHandlerRoutine(dwCtrlType);

	eProtectEndTrace();
	return bRet?TRUE:FALSE;
}

bool xbAppConsole::onBreakHandlerRoutine(ulong dwCtrlType)
{
	m_eventPtr.StopProcess();
	return true;
}

xbAppConsole::xbAppConsole(LPCSTR pszAppId,int _cArg,const char **_pArg,bool _bSilent,bool _bMbox,LPCSTR pszAppLabel,LPCSTR pszAppLogFile)
	:xbAppExe(pszAppId,pszAppLabel,pszAppLogFile),fout(xbStdStreamOUT),fin(xbStdStreamIN),ferr(xbStdStreamERR)
{
	cArg = _cArg-1;
	pArg = _pArg+1;
	bSilent = _bSilent;
	bMbox = _bMbox;
	bOpDone = false;

	appPath = _pArg[0];
	if (!SetConsoleCtrlHandler(BreakHandlerRoutine,TRUE))
		xbThrowEsys(xbHR_LAST,"SetConsoleCtrlHandler failed");
}

xbAppConsole::~xbAppConsole()
{
	eProtectBegin();
	if (!SetConsoleCtrlHandler(BreakHandlerRoutine,FALSE))
		xbThrowEsys(xbHR_LAST,"SetConsoleCtrlHandler/remove failed");
	eProtectEndTrace();
}

xbAppExe::xbAppExe(LPCSTR pszAppId,LPCSTR pszAppLabel,LPCSTR pszAppLogFile)
	:xbAppBase(pszAppId,pszAppLabel),
	m_cfgChangedCb(
	xbCbCast(xbCFGCHANGED,xbEngine,(xbCfgChangedCb &,xbCfgRoot,xbCfgKeyChangesInfo *,const xbString &),this,
	xbAppExe::receiveConfigChanged)
)
{
//	m_cfgChangedCb.Init(xbCfgCommon,GetConfigPath());
	m_pOldLogFile = NULL;
	m_cLogBuf = 0;
	m_pszAppLogFileDflt = pszAppLogFile;
}

xbAppExe::~xbAppExe()
{
	if (m_pOldLogFile)
		g_pxbLogFileName = m_pOldLogFile;
}

void xbAppExe::setLogFile(const xbString &logfile)
{
	xbSectLock lck(&m_sectCfg);
	if (!m_pOldLogFile)
		m_pOldLogFile = g_pxbLogFileName;
	xbString &logBuf = m_logBuf[(m_cLogBuf++)%xbAPPEXE_LOGFILEBUFCNT];
	logBuf = g_xbCfgEngine.GetExpandedString(logfile);
	g_pxbLogFileName = logBuf;
}

void xbAppExe::Start()
{
	m_coInit.Start();

	m_uselib.StartUse(&g_xbEngineCenter,true);
	
	m_eCtx.Set(this);

	readLogSettings(false);

	g_xbCfgEngine.AddConfigChangedCb(m_cfgChangedCb);
}

void xbAppExe::receiveConfigChanged(xbCfgChangedCb &cbObj,xbCfgRoot root,xbCfgKeyChangesInfo *pInfo,const xbString &cfgKeyPath)
{
	if ((root==xbCfgCommon || root==xbCfgAppli) && pInfo->HasPathChanged("log"))
	{
		readLogSettings(true);
	}
}

void xbAppExe::readLogSettings(bool bChg)
{
	xbString	logFile;
	long		cLogMax=g_xbLogFile_MaxCount_DFLT;
	long		cLogSize=g_xbLogFile_MaxKBsize_DFLT; //KB
	bool bKeyOk = false;
	xbCfgKey logkey(xbCfgAppli,"log");
	if (logkey.Exists())
		bKeyOk = true;
	else
	{
		logkey.Init(xbCfgCommon,"log");
		if (logkey.Exists())
			bKeyOk = true;
	}
	if (bKeyOk)
	{
		if (logkey.ValueExists("file"))
			logFile = logkey.Value["file"].AsString;
		if (logkey.ValueExists("max.kbsize"))
			cLogSize = logkey.Value["max.kbsize"].AsLong;
		if (logkey.ValueExists("max.count"))
			cLogMax = logkey.Value["max.count"].AsLong;
	}
	if (logFile.IsValid())
		setLogFile(logFile);
	else
	{
		if (!m_pszAppLogFileDflt)
			setLogFile(xbXDCSYSPATH xbPath_SLASH "logs" xbPath_SLASH "%xdcappname%.log");
		else
			setLogFile(m_pszAppLogFileDflt);
	}
	g_xbLogFile_MaxCount = cLogMax;
	g_xbLogFile_MaxKBsize = cLogSize;

	if (logFile.IsValid() || bChg)
	{
		g_bFirstOutput = true;
		g_cChg = 0;
	}

	if (bChg)
		xbRelOutput("config: log section changed (file="+logFile+", max.count="+xbString(cLogMax)+", max.kbsize="+xbString(cLogSize)+")");
}
