#include "TemplateNameParser.h"
#include <map>
#include <iostream>
#include <QSize>
#include "Des.h"
#include <string>
#include <vector>
#include "NameValidator.h"

namespace DESpot
{
	NameValidator TemplateNameParser::m_templateNameValidator(new AlphaNumValidator());
	NameValidator TemplateNameParser::m_NameValidator(new AlphaNumValidator(new WordSepValidator(new PercentValidator()))); 	
	
	TemplateNameParser::TemplateNameParser(const std::wstring& name):m_templateName(name)
	{
		m_variableIndex=0;
		m_currentIndex=0;
		m_variableName=new std::wstring();
		m_variablesName=new TemplateParameter;

	}

        TemplateNameParser::~TemplateNameParser(void)
	{
		m_variableName=null;
		m_variableIndex=0;
	}
	
	
	bool TemplateNameParser::isTemplateName()
	{
		start();
		int i=0;
		for(int m_countindex=0;m_countindex<m_templateName.size();m_countindex++)
		{
			if(m_templateName[m_countindex]==L'%')
			{
				i++;
			}
		}
			
		if((m_NameValidator.validate(m_templateName))&&(i%2==0)&&(i>0))
		{	
			return true;
		}
		else 
		{
			return false;
		}
	};

	void TemplateNameParser::matchPercent()
	{
		if(m_currentIndex<m_templateName.size()-2&&m_templateName[m_currentIndex]==L'%')
		{
			m_currentIndex++;
			m_variableName->append(m_templateName,m_currentIndex,1);
			if(m_templateNameValidator.validate2(*m_variableName)==false)
			{	
				throw EX("Error in variable name");
			}
			m_variablesName->insert(TemplateParameter::value_type(*m_variableName,L""));	
			m_currentIndex++;
			if(m_templateName[m_currentIndex]!=L'%')
			{
				throw EX("Error in Matching Percent in Template Name");
			}
			m_currentIndex++;
			m_variableName=new std::wstring();
			start();
		}	
		
	}
	void TemplateNameParser::start()
	{
		if(m_currentIndex<m_templateName.size())
		{
			RemoveOthers();
			matchPercent();
			
			
		}
	}
	
	void TemplateNameParser::RemoveOthers()
	{
		while(m_currentIndex<m_templateName.size()&&m_templateName[m_currentIndex]!=L'%')
		{
			if(m_currentIndex==m_templateName.size()-1)
			{
				break;
			}
			m_currentIndex++;
		}

	}
	
	TemplateNameParser::TemplateParameter* TemplateNameParser::extractVariables()
	{
		//TemplateNameParser* Parser = new TemplateNameParser(name);
		start();
		return m_variablesName;
	}
	
	TemplateNameParser::TemplateParameter* TemplateNameParser::getVariablesFromName(const std::wstring& name)
	{
		TemplateNameParser* Parser = new TemplateNameParser(name);
		return Parser->extractVariables();

	}





}
