// DM2RTextToken.cpp: CDM2RTextToken クラスのインプリメンテーション
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "dm2gded.h"
#include "DM2RTextToken.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// CDM2RTTokenList

bool CDM2RTTokenList::Parse(LPCTSTR pszText, int nRTM)
{
	CDM2RTTokenList tl;

	LPCSTR pszPos = pszText;
	LPCSTR pszEnd = strchr(pszPos, 0);

	while (pszPos < pszEnd) {
		BYTE c = *pszPos;
		int nRTT;
		switch (c) {
		case 'C': nRTT = rttC;
			if (!(nRTM & rtmC)) c = 0; //return false;
			break;
		case 'W': nRTT = rttWeapons;
			if (!(nRTM & rtmWeapons)) c = 0; //return false;
			break;
		case 'A': nRTT = rttClothes;
			if (!(nRTM & rtmClothes)) c = 0; //return false;
			break;
		case 'S': nRTT = rttScrolls;
			if (!(nRTM & rtmScrolls)) c = 0; //return false;
			break;
		case 'P': nRTT = rttPotions;
			if (!(nRTM & rtmPotions)) c = 0; //return false;
			break;
		case 'J': nRTT = rttMisc;
			if (!(nRTM & rtmMisc)) c = 0; //return false;
			break;
		default:
			c = 0;
		}
		if (c == 0) break;
		int nFrom, nTo;
		pszPos++;
		if (!ReadUInt(pszPos, pszEnd, nFrom))
			return false;
		if (*pszPos == '-') {
			pszPos++;
			if (*pszPos == c && c != 0)
				pszPos++;
			if (!ReadUInt(pszPos, pszEnd, nTo))
				return false;
			if (*pszPos == ' ') {
				pszPos++;
			} else if (pszPos == pszEnd) {

			} else {
				//return false;
			}
		} else if (*pszPos == ' ') {
			nTo = nFrom;
			pszPos++;
		} else if (pszPos == pszEnd) {
			nTo = nFrom;
		} else {
			nTo = nFrom;
			//return false;
		}
		int i = nFrom;
		while (i <= nTo) {
			tl.push_back(CDM2RTToken(nRTT, i));
			i++;
		}
	}
	swap(tl);
	return true;
}

bool CDM2RTTokenList::ReadUInt(LPCSTR &pszPos, LPCSTR pszEnd, int &x)
{
	x = 0;
	int i = 0;
	BYTE c;
	while (pszPos < pszEnd && isdigit(c = (BYTE)*pszPos) && i < 9) {
		x = x * 10 + (c - '0');
		i++;
		pszPos++;
	}
	if (i == 0)
		return false;
	return true;
}

CString CDM2RTTokenList::Mk() const
{
	CString strRet;
	CString strText;

	const_iterator
		iterPos = begin(),
		iterEnd = end();
	while (iterPos != iterEnd) {
		int nBaseRTT = iterPos->nRTT;
		int nIdxFrom = iterPos->iIdx;
		int nIdxTo = nIdxFrom;
		iterPos++;
		while (iterPos != iterEnd) {
			if (iterPos->nRTT == nBaseRTT && iterPos->iIdx == nIdxTo + 1) {
				nIdxTo++;
				iterPos++;
			} else {
				break;
			}
		}
		BYTE c = 0;
		switch (nBaseRTT) {
		case rttC:			c = 'C'; break;
		case rttWeapons:	c = 'W'; break;
		case rttClothes:	c = 'A'; break;
		case rttScrolls:	c = 'S'; break;
		case rttPotions:	c = 'P'; break;
		case rttMisc:		c = 'J'; break;
		}
		if (c != 0) {
			strText.Format((nIdxFrom == nIdxTo) ? "%c%d" : "%c%d-%d", c, nIdxFrom, nIdxTo);
			if (!strRet.IsEmpty()) strRet += " ";
			strRet += strText;
		}
	}

	return strRet;
}
