//
// Copyright (c) 2009 Froduald Kabanza and the Université de Sherbrooke.
// Use of this software is permitted for non-commercial research purposes, and
// it may be copied or applied only for that use. All copies must include this
// copyright message.
// 
// This is a research prototype that has not gone through intensive tests and
// is delivered as is. It may still contain bugs. Froduald Kabanza and the
// Université de Sherbrooke disclaim any responsibility for damage that may be
// caused by using it.
//
// Please note that some files were inspired in part by the PDDL4J library:
// http://www.math-info.univ-paris5.fr/~pellier/software/software.php 
//
// Implementation: Simon Chamberland
// Project Manager: Froduald Kabanza
//

#include "stdafx.h"
#include "FormulaApplication.h"
#include "../Term/Object.h"
#include "../UnaryFunctions.h"

using namespace planning;

FormulaApplication::~FormulaApplication()
{
  for (size_t i = 0; i < m_rootFormula->getArity(); ++i)
    m_arguments[i]->release(this);

  // Delete pointers!
  delete[] m_arguments;

  m_rootFormula->release(this);
}

const FormulaApplication* FormulaApplication::apply(const Bindings* bindings) const
{
  return dynamic_cast<const FormulaApplication*>(IExp::apply(bindings));
}

const IExp* FormulaApplication::_internalApply(const Bindings* bindings) const
{
  return m_rootFormula->getFormulaApplication(
    boost::transform_iterator<ApplyBindings<ITerm>, const_iterator>(m_arguments, bindings), 
    boost::transform_iterator<ApplyBindings<ITerm>, const_iterator>(m_arguments + m_rootFormula->getArity(), bindings));
}

const FormulaApplication* FormulaApplication::evaluateArguments(const IClosedWorld* world, 
                                                                const Bindings* bindings) const
{
  return m_rootFormula->evaluateArguments(m_arguments, m_arguments + m_rootFormula->getArity(), world, bindings);
}

size_t FormulaApplication::getArgumentsId() const
{
  assert(m_argumentsId != std::numeric_limits<size_t>::max());

  return m_argumentsId;
}

void FormulaApplication::setArgumentsId(size_t id)
{
  m_argumentsId = id;
}

FormulaId FormulaApplication::getFormulaId() const
{
  assert(m_argumentsId != std::numeric_limits<size_t>::max());

  return FormulaId(m_rootFormula->getOffset() + m_argumentsId);
}

int FormulaApplication::_internalCompareTo(const IExp& other) const
{
  const FormulaApplication& exp = dynamic_cast<const FormulaApplication&>(other);

  COMPARE(m_argumentsId, exp.m_argumentsId);

  COMPARE(m_rootFormula, exp.m_rootFormula);

  const size_t arity = m_rootFormula->getArity();
  for (size_t i = 0; i < arity; ++i)
  {
    COMPARE(m_arguments[i], exp.m_arguments[i]);
  }
  return 0;
}

void FormulaApplication::_output(std::ostream& out) const
{
  out << "(" << m_rootFormula->getName();
  for (size_t i = 0; i < m_rootFormula->getArity(); ++i)
  {
    out << " " << *m_arguments[i];
  }
  out << ")";
}
