/*
 * Copyright 2009 Funambol, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */
#include "DataStorageDefs.h"

#include <string>
#include <stdio.h>
#include <errno.h>

namespace NS_DM_Client
{

namespace NS_DataStorage
{

const DWORD c_maxEnvironmentStringSize = 1024;
	
//------------------------------------------------------------------------------------------------------
void str_replace(String& src, const String& what, const String& with)
{
	if (what != with) {
		String temp;
		String::size_type prev_pos = 0, pos = src.find(what, 0);
		while (String::npos != pos)
		{
			temp += String(src.c_str() + prev_pos, pos - prev_pos) + with;

			prev_pos = pos + what.size();
			pos = src.find(what, prev_pos);
		}
		if (!temp.empty())
		{
			src = temp + String(src.c_str() + prev_pos, src.length());
			if (String::npos == with.find(what))
			{
				str_replace(src, what, with);
			}
		}
	}
}
//------------------------------------------------------------------------------------------------------
bool ExpandStringWithEnvironmentVars(const String& in, String& out)
{
	bool res = false;
	
	char* buffer = (char*)malloc(c_maxEnvironmentStringSize);
	if (buffer)
	{
		// MSDN: When using ANSI strings, the buffer size should be the string length, plus terminating null character, plus one
		if (ExpandEnvironmentStringsA(in.c_str(), buffer, c_maxEnvironmentStringSize - 2) != 0)
		{
			out = buffer;
			res = true;	
		}
		free(buffer);
	}

	return res;
}

//------------------------------------------------------------------------------------------------------

}
}
