#include "../stdafx.h"
#include "../CreateStream.h"
#include "common/windows/FInStream.h"
#include "common/windows/FOutStream.h"
#include <windows.h>
#include <Psapi.h>

static const size_t INFO_BUFFER_SIZE  = 265;

namespace NS_Logging
{
	static const std::string S_logFilePath("%ALLUSERSPROFILE%/Funambol/DMClient/Logs/");
	static const std::string S_commonLogFile("_OMA_DM_Client.log");
	static const std::string S_slash("_");
	static const std::string S_ext(".log");

	std::string GetCurrentProcessName()
	{
		HANDLE curProcess = ::GetCurrentProcess();
		char processName[INFO_BUFFER_SIZE] = {0}; 
		DWORD res = ::GetModuleBaseNameA(curProcess, 0, processName, INFO_BUFFER_SIZE);
		if (res == 0)
			return S_commonLogFile;

		return processName;
	}

	NS_DM_Client::NS_Common::IOutStream* CreateOutStream()
	{
		NS_DM_Client::NS_Common::FOutStream* stream = new NS_DM_Client::NS_Common::FOutStream();
		char  buf[INFO_BUFFER_SIZE];
		// MSDN: When using ANSI strings, the buffer size should be the string length, plus terminating null character, plus one.
		::ExpandEnvironmentStringsA(S_logFilePath.c_str(), buf, INFO_BUFFER_SIZE - 2);
		std::string logFilePath = buf;

		int processID = ::GetCurrentProcessId();
		const int maxSize = 1024;
		char buffer[maxSize] = {0};
		_itoa_s(processID, buffer, 10);
		std::string processName = GetCurrentProcessName();

		std::string path = logFilePath;
		path += processName;
		path += S_slash;
		path += buffer;
		path += S_ext;
		stream->Open(path.c_str());
		return stream;
	}

	NS_DM_Client::NS_Common::IInStream* CreateInStream()
	{
		return new NS_DM_Client::NS_Common::FInStream();
	}
}
