#include "VarProcessor.h"

// merge a group of variables with another, replacing
// same names ones with the new ones
void VarProcessor::MergeVars(VectorMap<String, String> &v, VectorMap<String, String> const &news)
{
	for(int iVar = 0; iVar < news.GetCount(); iVar++)
		v.GetAdd(news.GetKey(iVar)) = news[iVar];
}

void VarProcessor::MergeVars(VectorMap<String, String> &v, String const &key, String const &value)
{
	v.GetAdd(key) = value;
}
		
// extract variables from a string
Vector<String> VarProcessor::ExtractVars(String const &s)
{
	Vector<String> res;
	int start = 0, end;
	while( (start = s.Find('{', start)) >= 0)
	{
		if( (end = s.Find('}', start + 1)) < 0)
			return res;
		res.Add(s.Mid(start + 1, end - start - 1));
		start = end + 1;
	}
	return res;
}

// substitute variables
String VarProcessor::SubstVars(String const &s, VectorMap<String, String> const &values)
{
	String res = s;
	
	// if string don't contain variables, do nothing
	if(s.Find('{') < 0)
		return s;
	
	// extract variables from string
	Vector<String> ext = ExtractVars(s);
	Vector<String> subst;
	
	// substitute each variable, if found in array
	for(int i = 0; i < ext.GetCount(); i++)
	{
		String curr = ext[i];
		int iCurr = values.Find(curr);
		if(iCurr >= 0)
		{
			// recursive substitution
			subst.Add(SubstVars(values[iCurr], values));
		}
		else
			subst.Add("{" + curr + "}");
	}
	
	
	for(int i = 0; i < ext.GetCount(); i++)
	{
		// @@ WORKAROUND FOR QUOTED VARIABLES
		// DIDN'T FIND A BETTER WAY BY NOW
		// KEEP QUOTES ESCAPING THEM ONLY FOR STRINGS LIKE ="{....}"
		res.Replace("=\"{" + ext[i] + "}\"", "=\\\"" + subst[i] + "\\\"");
		
		res.Replace("{" + ext[i] + "}", subst[i]);
	}
	return res;
}

String VarProcessor::SubstVars(String const &s, String const &subst)
{
	return "";
}

