/*
	ZazouMiniWebServer

	Copyright (C) 2003-2011 Xavier Garreau <xavier@xgarreau.org>

	This file is part of ZazouMiniWebServer.

    ZazouMiniWebServer is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    ZazouMiniWebServer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ZazouMiniWebServer; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
#include "stdafx.h"

#include <iostream>
#include <sstream>

#include "print_dbg.h"
#include "ZOSAL.h"

void print_dbg(const char* msg, OPER oper) {
	static CRITICAL_SECTION* stdHandlesCS = NULL;

	if (!stdHandlesCS) {
		stdHandlesCS = new CRITICAL_SECTION;
		InitializeCriticalSection(stdHandlesCS);
	}
	if (!msg && stdHandlesCS) {
		switch (oper) {
			case OPER_DELETE:
				if (stdHandlesCS) {
					DeleteCriticalSection(stdHandlesCS);
					stdHandlesCS = NULL;
				}
				return;
			case OPER_LOCK:
				EnterCriticalSection(stdHandlesCS);
				return;
			case OPER_UNLOCK:
				LeaveCriticalSection(stdHandlesCS);
				return;
			default: break;
		}
	}

	EnterCriticalSection(stdHandlesCS);
	{
		SYSTEMTIME  tActu;
		GetLocalTime(&tActu);

		std::stringstream tmpSS;
		if (tActu.wHour<10) tmpSS << "0";
		tmpSS << tActu.wHour << ":";
		if (tActu.wMinute<10) tmpSS << "0";
		tmpSS << tActu.wMinute << ":";
		if (tActu.wSecond<10) tmpSS << "0";
		tmpSS << tActu.wSecond << ": ";
		tmpSS << msg;
#ifdef WIN32
		HANDLE hOut;
		DWORD dummy;
		hOut = GetStdHandle (STD_OUTPUT_HANDLE);
		if (hOut && hOut != INVALID_HANDLE_VALUE) {
			WriteFile (hOut, tmpSS.str().c_str(), tmpSS.str().length(), &dummy, NULL);
		}
//		std::ofstream ofs("zmwsdebug.txt", std::ios_base::app | std::ios_base::ate);
//		ofs << tmpSS.str().c_str();
//		ofs.close();
#else
		std::cout << tmpSS.str().c_str();
#endif
	}
	LeaveCriticalSection(stdHandlesCS);
}

