/*<<<***************************************************************************
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: xbBase
#Project: xdcBase
////////////////////////////////////////////////////////////////////////////////
#Author: Marc MIRTI MANCINELLI
#History:
<15/09/2013: creation.
12/02/2014: this notice inserted.
***************************************************************************>>>*/
#include "stdafx.h"

#include "xbBase.h"
#include "xbException.h"
#include "xbFileTools.h"
#include "_xbVer.h"
#include "xbVersion.h"
#include "xbLibTools.h"

#pragma warning(push)
#pragma warning(disable: 4311)

extern void xbLogClose(FILE *fh,LPCSTR pLogFile);

volatile bool		g_bFirstOutput = true;
volatile DWORD		g_cChg = 0;

void xbRelOutput(const xbString &s,bool tofile)
{
	try
	{
		if (g_bFirstOutput && g_xbEngineCenter.IsReady())
		{
			g_bFirstOutput = false;
/*			SYSTEMTIME	time;
			memset(&time,0,sizeof(time));
			::GetSystemTime(&time);
			char buf[128];
			_snprintf(buf,sizeof(buf),"%d/%d/%04d %d:%02d:%02d.%03d",
				time.wDay,time.wMonth,time.wYear,time.wHour,time.wMinute,
				time.wSecond,time.wMilliseconds);*/
			xbString file(xbGetFilePath(NULL));
			xbRelOutput("²\n\n"
				"§p; ************************************************************************\n"
				"§p; ** xdcBase " XDCBASE_HSVER "." XDCBASE_LSVER " logs started ("
				+xbDateTime::UtcNow().ToString("UTC")
//				+xbString(buf)
				+")...\n"
				"§p; ** -> CALLER: "+xbGetProductName(file)+" ("+file+" - "+xbString(::GetCurrentProcessId(),xbStringNum_hexa)
					+" - "+xbString((xbNptr)::GetModuleHandle(file),xbStringNum_hexa)+").\n"
				"§p; ** -> OS: "+xbGetOSlabel()+".\n"
				"§p; ************************************************************************\n"
				);
		}
#ifndef XDCBASE_EMBED
		if (g_cChg != xbXdcLib::s_cChg)
		{
			g_cChg = xbXdcLib::s_cChg;

/*			SYSTEMTIME	time;
			memset(&time,0,sizeof(time));
			::GetSystemTime(&time);
			char buf[128];
			_snprintf(buf,sizeof(buf),"%d/%d/%04d %d:%02d:%02d.%03d",
				time.wDay,time.wMonth,time.wYear,time.wHour,time.wMinute,
				time.wSecond,time.wMilliseconds);*/
			xbString msg("²\n\n"
				"§p; ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"
				"§p; ++ xdcBase " XDCBASE_HSVER "." XDCBASE_LSVER " dll list changed ("
				+xbDateTime::UtcNow().ToString("UTC")
				//+xbString(buf)
				+")...\n");
			try
			{
				xbXdcLibEnum	enumlib;
				HMODULE hMod;
				while((hMod = enumlib.NextHlib()) != NULL)
				{
					xbString file(xbGetFilePath(hMod));
					msg += "§p; ++ -> Dll: "+xbGetProductName(file)
						+" ("+file+" - "
						+xbString((xbNptr)::GetModuleHandle(file),xbStringNum_hexa)+").\n";
				}
				msg += "§p; ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
				xbRelOutput(msg);

			}
			catch(xbEbase *e)
			{
				e->Delete();
			}
			catch(...)
			{
			}
		}
#endif
		xbString sp(xbFormat("%08lX",uint(::GetCurrentProcessId())));
		xbString st(xbFormat("%08lX.%04lX",uint(::xbThreadId()),::GetTickCount()));
		xbString sout(s);
		sout += '\n';
		if (sout.IsValid() && sout.GetAt(0) == '²')
		{
			sout = sout.Mid(1);

			sout.Replace("§p",(LPCSTR)sp);
			sout.Replace("§t",(LPCSTR)st);
		}
		else
		{
			xbString spt(sp);
			spt += '.';
			spt += st;
			spt += "; ";
			int pos = 0;
			for(;;)
			{
				sout.Insert(pos,spt);
				pos = sout.IndexOf('\n',pos);
				if (pos <= 0 || pos >= sout.Length - 1) 
					break;
				pos++;
			}
		}
#if defined(_DEBUG) || defined(_RELDBG)
		OutputDebugString(sout);
#endif
		if (!tofile || !g_pxbLogFileName) 
			return;
		FILE *fh = fopen(g_pxbLogFileName,"a+");
		if (!fh) 
		{
#if defined(_DEBUG) || defined(_RELDBG)
			try
			{
				OutputDebugString("Error in xbRelOutput(2): can't open log !! (");
				OutputDebugString(g_pxbLogFileName);
				OutputDebugString(")\n");
			}
			catch(...)
			{
			}
#endif
			return;
		}
		fputs(sout,fh);
		xbLogClose(fh,g_pxbLogFileName);
	}
	catch(xbEbase *e)
	{
		e->Delete();
#if defined(_DEBUG) || defined(_RELDBG)
		try
		{
			OutputDebugString("Error in xbRelOutput(1) !!\n");
		}
		catch(...)
		{
		}
#endif
	}
	catch(...)
	{
#if defined(_DEBUG) || defined(_RELDBG)
		try
		{
			OutputDebugString("Error in xbRelOutput(2) !!\n");
		}
		catch(...)
		{
		}
#endif
	}
}

void xbEXPORT xbRelOutputLow(LPCSTR pMsg)
{
	try
	{
		if (g_pxbLogFileName)
		{
			FILE *fh = fopen(g_pxbLogFileName,"a+");
			if (fh) 
			{
				fputs(pMsg,fh);
				fputs("\n",fh);
				xbLogClose(fh,g_pxbLogFileName);
			}
		}
#if defined(_DEBUG) || defined(_RELDBG)
		OutputDebugString(pMsg);
		OutputDebugString("\n");
#endif
	}
	catch(...)
	{
	}
}

void xbEXPORT xbRelOutputLowFmtV(LPCSTR pMsg, va_list ap)
{
	try
	{
		char buf[512];
		xbVsnprintf(buf,sizeof(buf)-1,pMsg,ap);
		buf[sizeof(buf)-1] = 0;

		if (g_pxbLogFileName)
		{
			FILE *fh = fopen(g_pxbLogFileName,"a+");
			if (fh) 
			{
				fputs(buf,fh);
				fputs("\n",fh);
				xbLogClose(fh,g_pxbLogFileName);
			}
		}
#if defined(_DEBUG) || defined(_RELDBG)
		OutputDebugString(buf);
		OutputDebugString("\n");
#endif
	}
	catch(...)
	{
	}
}

#if defined(_DEBUG) || defined(_RELDBG)
bool _xbCrtDbgReport(bool &bIgnore,
        const char * szFile,
        int nLine,
        const char * szFormat
        )
{
	xbString msg(szFormat);
	if (szFile)
		msg += "\nLocation: "+xbString(szFile)+"("+xbString(nLine)+")";
	xbDbgOutput("xbASSERT: "+msg);
	if (bIgnore)
		return false;

	if (xbIsDebuggerPresent())
	{
		msg += "\n\n- YES    : debugger\n- NO     : continue\n- CANCEL : hide messages";

		int ret = ::xbMBox(NULL,msg,"xdcBase System Warning",xbMBicon_Stop,xbMBbtn_YesNoCancel);
		if (ret == IDYES)
			::xbDebugBreak();
		else if (ret == IDCANCEL)
			bIgnore = true;
	}
	else
	{
		msg += "\n\n- OK     : continue\n- CANCEL : hide messages";

		int ret = ::xbMBox(NULL,msg,"xdcBase System Warning",xbMBicon_Stop,xbMBbtn_OkCancel);
		if (ret == IDCANCEL)
			bIgnore = true;
	}
	return false;
}
#endif

void xbLogClose(FILE *fh,LPCSTR pLogFile)
{
	long sz = ftell(fh);
	fclose(fh);
	if (sz < g_xbLogFile_MaxKBsize * 1024)
		return;

	int lgnum=-1;
	xbString sfilePrev;
	for(long i = g_xbLogFile_MaxCount; i >= 0; i--)
	{
		xbString sfile(pLogFile);
		if (i>0)
		{
			int pos = sfile.LastIndexOf('.');
			if (pos < 0)
				pos = sfile.Length;
			xbString snum(xbStrFromLong(i));
			if (lgnum<0)
				lgnum = snum.Length;

			sfile.Insert(pos,"-"+snum.RetPadLeft(lgnum,'0'));
		}
		if (sfilePrev.IsEmpty())
		{
			if (xbFileExists(sfile))
				::xbDeleteFile(sfile,xbOp_Required);
		}
		else
		{
			if (xbFileExists(sfile))
				::xbMoveFile(sfile,sfilePrev);
		}

		sfilePrev = sfile;
	}
}

#pragma warning(pop)
