/*<<<***************************************************************************
The MIT License (MIT)

Copyright(C) 2013 - 2015 Marc Mirti Mancinelli, Christophe Lardau and Philippe Pamart (xdcube.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, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

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 NONINFRINGEMENT. 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.
////////////////////////////////////////////////////////////////////////////////
#Title: xbConfigFileParser
#Project: xdcBase
////////////////////////////////////////////////////////////////////////////////
#Author: Marc MIRTI MANCINELLI
#History:
<14/09/2013: creation.
12/02/2014: this notice inserted.
***************************************************************************>>>*/
#include "stdafx.h"

#include "xbConfigFileParser.h"

#pragma warning(push)
#pragma warning(disable: 4311)
bool xbConfigFileParser::ParseStream(const xbString &fname,IxbInputStream *pStm)
{
	m_bXmlOk = true;
	ParseStart(createRootNode(),fname);
	xbString line;
	while(pStm->ReadStringA(&line)!=0)
	{
		line += "\n";
		Parse(line,line.Length);
	}
	ParseEnd();

	return m_bXmlOk;
}

void xbConfigFileParser::warning(const xbString &msg,int col,int line,LPCSTR pCtx)
{
	if (col < 0) col = m_col;
	if (line < 0) line = m_line;

	xbRelOutput(m_FileName + "(" + xbString(line) + ") : column = "+
		xbString(col)+", xbConfigFileParser::warning : "+msg);
}

void xbConfigFileParser::error(const xbString &msg,int col,int line,LPCSTR pCtx)
{
	if (col < 0) col = m_col;
	if (line < 0) line = m_line;

	if (m_pChgInfo)
		m_pChgInfo->errorAdd(msg,line,col);

	xbRelOutput(m_FileName + "(" + xbString(line) + ") : column = "+
		xbString(col)+", xbConfigFileParser::ERROR : "+msg);
	m_bXmlOk = false;
}

void xbConfigFileParser::cfgFileLoad(xbConfigFile *pKey)
{
	xbConfigLoadCtx chgCtx(m_pChgInfo);
	pKey->cfgFileLoad(&chgCtx,m_prRoot);
}

//IxbXmlTarget methods
void	xbConfigXmlNode::AddSection(sIxbXmlSource *pSrce,const xbString &name,bool bSectTerminated,const xbXmlPos &sectPos)
{
	switch(m_type)
	{
	case xbConfigXmlNode_Root:
		if (pSrce->Compare(name,"xdcube") == 0)
		{
			if (m_rootStatus == xbConfigXmlRoot_Undef
				&& !bSectTerminated)
			{
				m_rootStatus = xbConfigXmlRoot_Started;
				startSection(pSrce,this,xbString(),false,m_lastLine,sectPos);

				pSrce->PushTarget(this);
				return;
			}
			break;
		}
		if (m_rootStatus != xbConfigXmlRoot_Started)
			break;
	default:
		{
			xbConfigFileParser *pParser;
			::xbCastInReq(pSrce,&pParser);

			xbRefPtr<xbConfigXmlNode> prNode(pParser->createNode());
			m_arrNode.Add(prNode);
			prNode->InitNode(xbConfigXmlNode_Undef,m_cp);

			prNode->startSection(pSrce,this,name,bSectTerminated,m_lastLine,sectPos);

			if (!bSectTerminated)
				pSrce->PushTarget(prNode);
			return;
		}
		break;
	}

	xbThrow xbExmlParser("Invalid section '"+name+"' found");
}
void	xbConfigXmlNode::AddSectionEnd(sIxbXmlSource *pSrce,const xbString &name,const xbXmlPos &sectPos)
{
	switch(m_type)
	{
	case xbConfigXmlNode_Root:
		if (pSrce->Compare(name,"xdcube") == 0)
		{
			if (m_rootStatus == xbConfigXmlRoot_Started)
			{
				m_rootStatus = xbConfigXmlRoot_Stopped;
				pSrce->PopTarget(this);
				return;
			}
			break;
		}
		break;
	default:
		if (pSrce->Compare(m_fullName,name) == 0)
		{
			pSrce->PopTarget(this);
			endSection(pSrce,m_lastLine,sectPos);
			return;
		}
		break;
	}

	xbThrow xbExmlParser("Invalid section end '"+name+"' found");
}

void	xbConfigXmlNode::startSection(sIxbXmlSource *pSrce,xbConfigXmlNode *pParent,const xbString &name,bool bSectTerminated,int &lastLine,const xbXmlPos &sectPos)
{
	if (lastLine>0)
	{
		m_cLf = sectPos.m_line - lastLine - 1;
		if (m_cLf < 0)
			m_cLf = 0;
		else if (m_cLf > 10)
			m_cLf = 10;
	}
	else
		m_cLf = 0;
	lastLine = pSrce->GetCurrentPosition().m_line; //sectPos.m_line;
	m_lastLine = lastLine;
	m_textColStart = sectPos.m_col;
	xbRdbgAssert(m_name.IsEmpty());
	if (m_type == xbConfigXmlNode_Root)
	{
		xbRdbgAssert(name.IsEmpty());
		xbRdbgAssert(m_rootStatus == xbConfigXmlRoot_Started);
	}
	else
	{
		if (pSrce->IsSectComment())
		{
			xbRdbgAssert(bSectTerminated);
			m_type = xbConfigXmlNode_Comment;
			m_name = name;
			return;
		}

		xbRdbgAssert(name.IsValid());
		int posSep = name.IndexOf(':');
		if (posSep>=0)
		{
			m_type = xbConfigXmlNode_Value;
			m_valMode = bSectTerminated?xbCfgVal_AsSectionValue:xbCfgVal_AsSection;

			xbString keyName = name.Left(posSep);
			xbString valName = name.Mid(posSep+1);

			if (!xbConfigNode::xmlValueNameIsValid(valName))
				xbThrow xbExmlParser("Value with an invalid name ('"+valName+"') found in configuration file");

			xbString parentName(pParent->GetName());
			if (pSrce->Compare(keyName,parentName) != 0)
				xbThrow xbExmlParser("Section with an invalid name ('"+name+"') found in configuration file");

			m_name = valName;
			m_fullName = name;
			if (!bSectTerminated)
			{
				pSrce->SetSectIgnore(true);
				pSrce->SetTextTrim(false);
			}
		}
		else
		{
			m_type = xbConfigXmlNode_Key;
			if (!xbConfigNode::xmlKeyNameIsValid(name))
				xbThrow xbExmlParser("Key with an invalid name ('"+name+"') found in configuration file");

			m_fullName = name;
			m_name = name;
		}
	}

	bool bValFound = false,bNoEscapeFound = false;
	int idx=0;
	xbXmlFlag *pFlag;
	while(pSrce->EnumFlag(idx,&pFlag))
	{
		xbString sname(pFlag->GetUnescName(m_cp));

		if (m_type == xbConfigXmlNode_Value)
		{
			if (m_valMode == xbCfgVal_AsSectionValue)
			{
				if (bValFound || pSrce->Compare(sname,"value") != 0)
					xbThrow xbExmlParser("Invalid syntax for section value '"+name+"', tag '"+sname+"' unexpected !");
				bValFound = true;
			}
			else
			{
				if (bNoEscapeFound || pSrce->Compare(sname,"noescape") != 0 || pFlag->HasValue())
					xbThrow xbExmlParser("Invalid syntax for section value '"+name+"', tag '"+sname+"' unexpected !");

				bNoEscapeFound = true;
				m_valMode = xbCfgVal_AsSectionNoEncode;
				continue;
			}			
		}
		else
		{
			if (!xbConfigNode::xmlValueNameIsValid(sname))
				xbThrow xbExmlParser("Value with an invalid name ('"+sname+"') found in configuration file");
		}
		
		int tagIdx = m_arrTag.IncLength();
		Tag &tag = m_arrTag.GetAt(tagIdx);

		tag.m_name = sname;

		xbStringW sval(pFlag->GetUnescValueW(m_cp));
		tag.m_value.AsXmlStringW = sval;
	}
}

void	xbConfigXmlNode::endSection(sIxbXmlSource *pSrce,int &lastLine,const xbXmlPos &sectPos)
{
	if (m_type == xbConfigXmlNode_Root)
		xbThrow xbExmlParser("unexpected call to xbConfigXmlNode::endSection, node type = root");

	pSrce->SetSectIgnore(false);
	pSrce->SetTextTrim(true);

	if (m_type == xbConfigXmlNode_Value)
	{
		xbRdbgAssert(m_valMode == xbCfgVal_AsSectionNoEncode || m_valMode == xbCfgVal_AsSection);

		xbStringW sval(textTrunc(pSrce,m_text));
		if (m_valMode == xbCfgVal_AsSection)
			sval = ::xbHtmlUnescape(sval);

		xbRdbgAssert(m_arrTag.IsEmpty());

		int tagIdx = m_arrTag.IncLength();
		Tag &tag = m_arrTag.GetAt(tagIdx);
		tag.m_name = "value";
		tag.m_value.AsXmlStringW = sval;

		if (lastLine == sectPos.m_line)
		{
			if (m_valMode == xbCfgVal_AsSectionNoEncode)
				m_valMode = xbCfgVal_AsSectionOneLineNoEncode;
			else
				m_valMode = xbCfgVal_AsSectionOneLine;
		}
	}
	lastLine = sectPos.m_line;
	xbRefQIPtr<xbConfigXmlNode> prParent(pSrce->GetTarget());
	prParent->m_lastLine = lastLine;
}

void	xbConfigXmlNode::AddText(sIxbXmlSource *pSrce,const xbString &text,const xbXmlPos &textPos)
{
	if (m_type != xbConfigXmlNode_Value)
		xbThrow xbExmlParser("unexpected text in section '"+GetXmlLabel(pSrce)+"'");

	m_text += xbStringW(m_cp,text);
}

int		xbConfigXmlNode::CutSectionName(sIxbXmlSource *pSrce,const xbString &name,bool bEndSection,bool bSectTerminated)
{
	return -1;
}

bool	xbConfigXmlNode::Warning(const xbString &file,int col,int line,const xbString &msg,LPCSTR pCtx)
{
	return false;
}
bool	xbConfigXmlNode::Error(const xbString &file,int col,int line,const xbString &msg,LPCSTR pCtx)
{
	return false;
}

void	xbConfigXmlNode::EndParse(sIxbXmlSource *pSrce,bool bOk)
{
}

xbString xbConfigXmlNode::GetXmlLabel(sIxbXmlSource *pSrce)
{
	if (m_type == xbConfigXmlNode_Root
		&& m_rootStatus == xbConfigXmlRoot_Started)
		return "xdcube";

	return m_fullName;
}

//Implementation
bool xbConfigXmlNode::EnumTagAndDetachVal(int &idx,xbString *pName, xbVariant *pValue,int *pOrder)
{
	if (idx >= m_arrTag.Length)
		return false;
	Tag &tag = m_arrTag.GetAt(idx);
	if (pName)
		*pName = tag.m_name;
	if (pValue)
		pValue->Attach(tag.m_value.IOaddr());

	if (pOrder)
		*pOrder = idx;
	idx++;
	return true;
}
bool xbConfigXmlNode::EnumSection(int &idx,xbRefPtr<xbConfigXmlNode> *pprKey) const
{
	if (idx >= m_arrNode.Length)
		return false;
	if (pprKey)
		*pprKey = m_arrNode.GetAt(idx);

	idx++;
	return true;
}
void xbConfigXmlNode::GetValueAndDetach(xbVariant *pVar)
{
	xbRdbgAssert(m_type == xbConfigXmlNode_Value);
	xbRdbgAssert(m_arrTag.Length == 1 && m_arrTag.GetAt(0).m_name.CompareNC("value") == 0);

	pVar->Attach(m_arrTag.GetAt(0).m_value.IOaddr());
}

void xbConfigXmlNode::GetComment(xbStringW *pComment)
{
	xbRdbgAssert(m_type == xbConfigXmlNode_Comment);
	*pComment = xbStringW(m_cp,m_name);
}

void xbConfigXmlNode::Clear(xbArray< xbRefPtr<IxbObject> > *pArrNodeRsrv)
{
	m_type = xbConfigXmlNode_Undef;
	m_valMode = xbCfgVal_Auto;
	m_cLf = 0;
	m_textColStart = 0;
	m_cp = 0;
	m_rootStatus = xbConfigXmlRoot_Undef;
	m_lastLine = 0;
	m_name.Empty();
	m_fullName.Empty();
	m_text.Empty();

	m_arrTag.Empty();
	
	xbArray< xbRefPtr<xbConfigXmlNode> > arrNode;
	arrNode.Attach(&m_arrNode);

	xbRefPtr<xbConfigXmlNode>	*pptr = arrNode.Begin();
	xbRefPtr<xbConfigXmlNode>	*ppend = arrNode.End();
	while(pptr < ppend)
	{
		(*pptr)->Clear(pArrNodeRsrv);
		pptr++;
	}

	if (pArrNodeRsrv)
		pArrNodeRsrv->Add((IxbXmlTarget*)this);
}

void xbConfigXmlNode::InitNode(xbConfigXmlNodeType nodeType,ulong cp)
{
	m_type = nodeType;
	m_cp = cp;
}

xbConfigFileParser::xbConfigFileParser(ulong cp,xbCfgKeyChangesInfo *pChgInfo,xbArray< xbRefPtr<IxbObject> > *pArrNodeRsrv)
{
	m_cp = cp;
	m_pChgInfo = pChgInfo;
	m_pArrNodeRsrv = pArrNodeRsrv;
	m_bXmlOk = false;
	m_bTrimText = false;
}

xbConfigFileParser::~xbConfigFileParser()
{
	eProtectBegin();

	if (m_prRoot.IsValid())
	{
		m_prRoot->Clear(m_pArrNodeRsrv);
		m_prRoot.Empty();
	}

	m_pArrNodeRsrv = NULL;
	eProtectEndTrace();
}

IxbXmlTarget *xbConfigFileParser::createRootNode()
{
	xbRefPtr<xbConfigXmlNode> prNode(createNode());
	prNode->InitNode(xbConfigXmlNode_Root,m_cp);
	m_prRoot = prNode;
	return m_prRoot;
}

xbRefPtr<xbConfigXmlNode> xbConfigFileParser::createNode()
{
	if (m_pArrNodeRsrv->IsValid())
	{
		xbRefQIPtr<xbConfigXmlNode> prNode(m_pArrNodeRsrv->Last());
		m_pArrNodeRsrv->Length = m_pArrNodeRsrv->Length - 1;
		return (xbConfigXmlNode*)prNode;
	}

	xbRefPtr<xbConfigXmlNode> prNode;
	xbConfigXmlNode::CreateObject(&prNode);
	return prNode;
}

xbStringW xbConfigXmlNode::textTrunc(sIxbXmlSource *pSrce,const xbStringW &str)
{
	if (str.IndexOf(L'\n')<0)
		return str;

	xbStringW ret(str);
	if (ret.First() == L'\n')
		ret.Delete(0);

	if (ret.IsValid() && ret.Last() == L'\n')
		ret.Delete(ret.Length-1);
	int pos = 0;
	for(;;)
	{
		LPCWSTR pStr = ret;
		pStr += pos;
		LPCWSTR pStart = pStr;

		int col = 0;
		while(col < m_textColStart
			&& (*pStr == L' ' || *pStr == '\t'))
		{
			if (*pStr == L' ')
				col++;
			else
				col = pSrce->TabAlign(col+1);
			pStr++;
		}
		if (pStr > pStart)
			ret.Delete(pos,(int)((xbNptr(pStr) - xbNptr(pStart))/sizeof(*pStr)));

		pos = ret.IndexOf(L'\n',pos);
		if (pos < 0)
			break;
		pos++;
	}
	return ret;
}
#pragma warning(pop)
