/* "CodeWorker":	a scripting language for parsing and generating text.

Copyright (C) 1996-1997, 1999-2002 Cédric Lemaire

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

To contact the author: codeworker@free.fr
*/

#ifdef WIN32
#pragma warning (disable : 4786)
#endif

#include "UtlException.h"
#include "ScpStream.h"

#include "DtaScriptVariable.h"
#include "GrfFunction.h"
#include "CppCompilerEnvironment.h"
#include "DtaScript.h" // declaration of 'GrfScriptBlock'
#include "GrfBlock.h"

namespace CodeWorker {
	GrfBlock::~GrfBlock() {
		clear();
	}

	DtaScript* GrfBlock::getScript() const {
		const GrfBlock* pBlock = this;
		while (pBlock->_pScript == 0L) {
			pBlock = pBlock->getParent();
			if (pBlock == 0L) return 0L;
		}
		return pBlock->_pScript;
	}

	void GrfBlock::clear() {
		for (std::vector<GrfCommand*>::iterator i = _commands.begin(); i != _commands.end(); i++) {
			delete (*i);
		}
		for (std::list<GrfCommand*>::iterator j = _functions.begin(); j != _functions.end(); j++) {
			GrfCommand* pFunction = *j;
			*j = 0L;
			delete pFunction;
		}
		_commands = std::vector<GrfCommand*>();
		_functions = std::list<GrfCommand*>();
	}

	void GrfBlock::applyRecursively(APPLY_ON_COMMAND_FUNCTION apply) {
		GrfCommand::applyRecursively(apply);
		for (std::vector<GrfCommand*>::iterator i = _commands.begin(); i != _commands.end(); i++) (*i)->applyRecursively(apply);
		for (std::list<GrfCommand*>::iterator j = _functions.begin(); j != _functions.end(); j++) (*j)->applyRecursively(apply);
	}

	void GrfBlock::add(GrfCommand* pCommand) {
		pCommand->setParent(this);
		_commands.push_back(pCommand);
	}

	void GrfBlock::setCommand(int i, GrfCommand* pCommand) {
		_commands[i] = pCommand;
		pCommand->setParent(this);
	}

	void GrfBlock::moveCommands(GrfBlock& destinationBlock) {
		while (!_commands.empty()) {
			GrfCommand* pCommand =  _commands.back();
			pCommand->setParent(&destinationBlock);
			destinationBlock._commands.push_back(pCommand);
			_commands.pop_back();
		}
	}

	bool GrfBlock::removeCommand(GrfCommand* pCommand) {
		for (std::vector<GrfCommand*>::iterator i = _commands.begin(); i != _commands.end(); i++) {
			if (*i == pCommand) {
				delete *i;
				_commands.erase(i);
				return true;
			}
		}
		return false;
	}

	GrfFunction* GrfBlock::addFunction(const std::string& sFunctionName, const std::string& sTemplate, bool bGenericKey) {
		int iArity;
		GrfFunction* pFunction = getFunction(sFunctionName, sTemplate, bGenericKey, iArity);
		if (pFunction != 0L) return 0L;
		pFunction = new GrfFunction(this, sFunctionName, sTemplate, bGenericKey);
		_functions.push_back(pFunction);
		return pFunction;
	}

	GrfFunction* GrfBlock::addFunction(GrfFunction* pFunction) {
		int iArity;
		if (getFunction(pFunction->getFunctionName(), pFunction->getTemplateInstantiation(), pFunction->isGenericKey(), iArity) != 0L) return 0L;
		_functions.push_back(pFunction);
		return pFunction;
	}

	GrfFunction* GrfBlock::getFunction(const std::string& sFunctionName, const std::string& sTemplate, bool bGenericKey, int& iArity) {
		for (std::list<GrfCommand*>::const_iterator i = _functions.begin(); i != _functions.end(); i++) {
			GrfFunction* pFunction = (GrfFunction*) (*i);
			if (pFunction->getName() == sFunctionName) {
				if (pFunction->isGenericKey()) {
					if (bGenericKey) {
						iArity = pFunction->getArity();
						return pFunction;
					}
				} else if (pFunction->getTemplateInstantiation() == sTemplate) {
					iArity = pFunction->getArity();
					return pFunction;
				}
			}
		}
		if (getParent() != 0L) return getParent()->getFunction(sFunctionName, sTemplate, bGenericKey, iArity);
		iArity = 0;
		return 0L;
	}

	bool GrfBlock::removeFunction(const std::string& sFunctionName, const std::string& sTemplateInstantiation) {
		for (std::list<GrfCommand*>::iterator i = _functions.begin(); i != _functions.end(); i++) {
			GrfFunction* pFunction = (GrfFunction*) (*i);
			if ((pFunction != 0L) && (pFunction->getName() == sFunctionName) && (pFunction->getTemplateInstantiation() == sTemplateInstantiation)) {
				delete *i;
				_functions.erase(i);
				return true;
			}
		}
		return false;
	}

	bool GrfBlock::removeGenericTemplateFunction(const std::string& sFunctionName) {
		for (std::list<GrfCommand*>::iterator i = _functions.begin(); i != _functions.end(); i++) {
			GrfFunction* pFunction = (GrfFunction*) (*i);
			if ((pFunction != 0L) && (pFunction->getName() == sFunctionName) && pFunction->isGenericKey()) {
				delete *i;
				_functions.erase(i);
				return true;
			}
		}
		return false;
	}

	void GrfBlock::moveFunctions(GrfBlock& destinationBlock) {
		while (!_functions.empty()) {
			GrfFunction* pFunction = (GrfFunction*) _functions.front();
			destinationBlock.removeFunction(pFunction->getName(), pFunction->getTemplateInstantiation());
			pFunction->setParent(&destinationBlock);
			destinationBlock._functions.push_back(pFunction);
			_functions.pop_front();
		}
	}

	SEQUENCE_INTERRUPTION_LIST GrfBlock::executeInternal(DtaScriptVariable& visibility) {
		SEQUENCE_INTERRUPTION_LIST result = NO_INTERRUPTION;
		if (_bHasLocalVariables) {
			DtaScriptVariable localVariables(&visibility, "##stack## block");
			for (std::vector<GrfCommand*>::iterator i = _commands.begin(); i != _commands.end(); i++)
				if ((result = (*i)->execute(localVariables)) != NO_INTERRUPTION) break;
		} else {
			for (std::vector<GrfCommand*>::iterator i = _commands.begin(); i != _commands.end(); i++)
				if ((result = (*i)->execute(visibility)) != NO_INTERRUPTION) break;
		}
		return result;
	}

	SEQUENCE_INTERRUPTION_LIST GrfBlock::executeAt(DtaScriptVariable& visibility, int iPosition) {
		SEQUENCE_INTERRUPTION_LIST result = NO_INTERRUPTION;
		if (_bHasLocalVariables) {
			DtaScriptVariable localVariables(&visibility, "##stack## block");
			for (std::vector<GrfCommand*>::iterator i = _commands.begin() + iPosition; i != _commands.end(); i++)
				if ((result = (*i)->execute(localVariables)) != NO_INTERRUPTION) break;
		} else {
			for (std::vector<GrfCommand*>::iterator i = _commands.begin() + iPosition; i != _commands.end(); i++)
				if ((result = (*i)->execute(visibility)) != NO_INTERRUPTION) break;
		}
		return result;
	}

	SEQUENCE_INTERRUPTION_LIST GrfBlock::executeInto(DtaScriptVariable& visibility, int iStart, int iEnd) {
		SEQUENCE_INTERRUPTION_LIST result = NO_INTERRUPTION;
		for (int i = iStart; i <= iEnd; i++) {
			result = _commands[i]->execute(visibility);
			if (result != NO_INTERRUPTION) break;
		}
		return result;
	}

	void GrfBlock::compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const {
		if ((!_functions.empty()) && (dynamic_cast<const GrfScriptBlock*>(this) == 0)) {
			std::string sMessage = "\"";
			if (this->_sParsingFilePtr != 0) {
				sMessage += this->_sParsingFilePtr;
			} else {
				sMessage += theCompilerEnvironment.getCurrentScriptSession()._sFilename;
			}
			sMessage += "\": C++ generation doesn't admit a function definition into a block of instructions;\nplease move the following one to the primary scope of the script:\n";
			for (std::list<GrfCommand*>::const_iterator i = _functions.begin(); i != _functions.end(); i++) {
				sMessage += "\t- " + dynamic_cast<GrfFunction*>(*i)->getSignature() + "\n";
			}
			throw UtlException(sMessage);
		}
		bool bBrackets = theCompilerEnvironment.bracketsToNextBlock();
		bool bCarriage = theCompilerEnvironment.carriageReturnAfterBlock();
		if (!bCarriage) theCompilerEnvironment.carriageReturnAfterBlock(true);
		if (bBrackets) {
			theCompilerEnvironment.incrementIndentation();
			CW_BODY_STREAM << "{";
			if (!_commands.empty()) CW_BODY_ENDL;
		} else {
			theCompilerEnvironment.bracketsToNextBlock(true);
		}
		std::vector<GrfCommand*>::const_iterator i;
		for (i = _commands.begin(); i != _commands.end(); i++) {
			(*i)->compileCpp(theCompilerEnvironment);
		}
		if (bBrackets) {
			theCompilerEnvironment.decrementIndentation();
			CW_BODY_INDENT << "}";
			if (bCarriage) CW_BODY_ENDL;
		}
	}

	void GrfBlock::compileCppFunctions(CppCompilerEnvironment& theCompilerEnvironment) const {
		for (std::list<GrfCommand*>::const_iterator i = _functions.begin(); i != _functions.end(); i++) {
			theCompilerEnvironment.newFunction(dynamic_cast<GrfFunction*>(*i));
		}
		for (std::list<GrfCommand*>::const_iterator j = _functions.begin(); j != _functions.end(); j++) {
			(*j)->compileCpp(theCompilerEnvironment);
		}
	}

	void GrfBlock::compileCppBNFSequence(CppCompilerEnvironment& theCompilerEnvironment) const {
		std::vector<GrfCommand*>::const_iterator i = getCommands().begin();
		for (;;) {
			(*i)->compileCpp(theCompilerEnvironment);
			i++;
			if (i == getCommands().end()) break;
			CW_BODY_INDENT << "if (_compilerClauseSuccess) {";CW_BODY_ENDL;
			theCompilerEnvironment.incrementIndentation();
		}
		int j = getNbCommands() - 1;
		while (j > 0) {
			theCompilerEnvironment.decrementIndentation();
			CW_BODY_INDENT << "}";CW_BODY_ENDL;
			j--;
		}
	}

	void GrfBlock::compileCppBetween(CppCompilerEnvironment& theCompilerEnvironment, int iStart, int iEnd) const {
		std::vector<GrfCommand*>::const_iterator i;
		std::vector<GrfCommand*>::const_iterator endIterator = _commands.begin() + iEnd;
		for (i = _commands.begin() + iStart; i != endIterator; i++) {
			(*i)->compileCpp(theCompilerEnvironment);
		}
	}

	void GrfBlock::compileCppAt(CppCompilerEnvironment& theCompilerEnvironment, int iStart) const {
		std::vector<GrfCommand*>::const_iterator i;
		for (i = _commands.begin() + iStart; i != _commands.end(); i++) {
			(*i)->compileCpp(theCompilerEnvironment);
		}
	}
}
