/******************************************************************************
 *    GetParamBool.cpp
 *
 *    This file is part of Object Script Library
 *    Copyright (C) 2005-2009 Tom N Harris <telliamed@whoopdedo.org>
 *
 *    Permission is hereby granted, free of charge, to any person obtaining
 *    a copy of this software and associated documentation files (the 
 *    "Software"), to deal in the Software without restriction, including 
 *    without limitation the rights to use, copy, modify, merge, publish, 
 *    distribute, sublicense, and/or sell copies of the Software, and to 
 *    permit persons to whom the Software is furnished to do so.
 *    
 *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
 *    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
 *    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-
 *    INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 
 *    BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN 
 *    AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
 *    IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *    THE SOFTWARE.
 *
 *****************************************************************************/

#include "ScriptLib.h"

#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <malloc.h>

extern const char* g_pszParamDelim;
extern const char* g_pszQuotes;

bool GetParamBool(const char* pszString, const char* pszParam, bool bDefault)
{
	if (!pszString || !pszParam)
		return bDefault;
	bool bRet = bDefault;
	char* pszTemp = reinterpret_cast<char*>(alloca(strlen(pszString)+1));
	if (!pszTemp)
		return false;
	strcpy(pszTemp, pszString);
	char* pszSep, *pszToken;
	for (pszSep = pszTemp, pszToken = strqsep(&pszSep, g_pszParamDelim, g_pszQuotes); 
	     pszToken; pszToken = strqsep(&pszSep, g_pszParamDelim, g_pszQuotes))
	{
		while (isspace(*pszToken)) ++pszToken;
		char* pszStart = strchr(pszToken, '=');
		if (pszStart)
			*pszStart++ = '\0';
		if (!stricmp(pszToken, pszParam))
		{
			if (!pszStart)
				break;
			while (isspace(*pszStart)) ++pszStart;
			char* pszEnd = pszStart + strlen(pszStart);
			if (*pszStart == '\"' || *pszStart == '\'')
			{
				if (*(pszEnd-1) == *pszStart)
					*(--pszEnd) = '\0';
				++pszStart;
			}
			switch (*pszStart)
			{
			case '1': case 't': case 'T': case 'y': case 'Y':
				bRet = true;
				break;
			case '$':
			{
				++pszStart;
				if (pszEnd > pszStart)
				{
					SService<IQuestSrv> pQS(g_pScriptManager);
					if (pQS->Exists(pszStart))
						bRet = pQS->Get(pszStart);
				}
				break;
			}
			default:
				bRet = strtol(pszStart, NULL, 0);
				break;
			}
			break;
		}
	}
	return bRet;
}
