#include "stdafx.h"
#include "stringmap.h"

StringMap::StringMap(void)
{
}

StringMap::~StringMap(void)
{
	Clear();
}

const TCHAR * StringMap::Find(const TCHAR * key)
{
	std::list<StringMapElement *>::iterator i;

	for(i=map.begin();i!=map.end();i++){
		StringMapElement * p = *i;
		if(p->key==key){
			return p->data.data();
		}	
	}
	return NULL;
}

void StringMap::Insert(const TCHAR * key, const TCHAR * data)
{
	StringMapElement * p = new StringMapElement;
	p->key = key;
	p->data = data;
	map.push_back(p);
}

void StringMap::Remove(const TCHAR * key)
{
	std::list<StringMapElement *>::iterator i;

	for(i=map.begin();i!=map.end();i++){
		StringMapElement * p = *i;
		if(p->key==key){
			delete p;
			map.erase(i);
			break;
		}
	}
}

void StringMap::Clear()
{
	std::list<StringMapElement *>::iterator i;

	for(i=map.begin();i!=map.end();i++){
		delete *i;
	}

	map.clear();
}

// not thread safe
const TCHAR * StringMap::Map(const TCHAR * text)
{
	static std::wstring buffer;

	std::list<StringMapElement *>::iterator i;

	buffer = text;
	for(i=map.begin();i!=map.end();i++){
		std::wstring::size_type pos = 0;
		std::wstring::size_type npos = -1;
		StringMapElement * p = *i;
			
		while((pos = buffer.find(p->key,0))!=npos){
			buffer.erase(pos,p->key.length());
			buffer.insert(pos,p->data);
		}
		
	}

	return buffer.data();
}