#include "StdAfx.h"
#include "keyswapstring.h"

CKeySwapString::CKeySwapString(void)
{
}

CKeySwapString::~CKeySwapString(void)
{
}

/*!
	置き換え文字列を設定する
*/
void CKeySwapString::SetString(CString str)
{
	int index,next,before=0;

	while(1)
	{
		index = str.Find("%",before);
		if(index == -1)
		{
			m_lastString = str.Mid(before);
			break;
		}
		else
		{
			next = str.Find("%",index + 1);
			if(next == -1)
			{
				m_lastString = str.Mid(before);
				break;
			}

			m_swapList.AddTail(CSwapItem(str.Mid(before,index-before),str.Mid(index+1,next-index-1)));

			before = next + 1;
		}
	}
}

/*!
	置き換え後の文字列を取得
*/
CString CKeySwapString::GetString(CString noData)
{
	CString	ret;

	POSITION pos = m_swapList.GetHeadPosition();
	if(pos == NULL)
		return("");

	for (int i=0;i<m_swapList.GetCount();i++)
	{
		POSITION old = pos;
		if(m_swapList.GetNext(pos).m_swapped == 0)
		{
			ret += m_swapList.GetAt(old).m_beforeString;

			if(noData.IsEmpty())
				ret += m_swapList.GetAt(old).m_keyString;
			else
				ret += noData;
		}
		else
		{
			ret += m_swapList.GetAt(old).m_beforeString;
			ret += m_swapList.GetAt(old).m_keyString;
		}
	}

	return(ret + m_lastString);
}

/*!
	置き換えを実行する
*/
void CKeySwapString::Swap(CWorkspaceAccess swap)
{
	if(KeyAvailable()==0)
		return;

	CKeyDataArray keyData;
	swap.CopyAllKeys(keyData);

	for(int i=0;i<keyData.GetSize();i++)
		_Swap(keyData[i].m_key,keyData[i].m_data);

}


/*!
	置き換えを実行する
*/
void CKeySwapString::Swap(CString key,CString data)
{
	_Swap(key,data);
}

/*!
	置き換えを実行する
*/
void CKeySwapString::_Swap(CString &key,CString &data)
{
	POSITION pos = m_swapList.GetHeadPosition();
	if(pos == NULL)
		return;

	for (int i=0;i<m_swapList.GetCount();i++)
	{
		POSITION old = pos;
		if(m_swapList.GetNext(pos).m_swapped == 0)
		{
			if(m_swapList.GetAt(old).m_keyString == key)
			{
				m_swapList.GetAt(old).m_keyString = data;
				m_swapList.GetAt(old).m_swapped = 1;
				break;
			}
		}
	}
}


/*!
	キーの残りを取得する
*/
int CKeySwapString::KeyAvailable()
{
	POSITION pos = m_swapList.GetHeadPosition();
	if(pos == NULL)
		return(0);

	int	count = 0;
	for (int i=0;i<m_swapList.GetCount();i++)
	{
		if(m_swapList.GetNext(pos).m_swapped == 0)
			count++;
	}

	return(count);
}
