//
// 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 this file was 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 "ExistsExp.h"
#include "OrExp.h"
#include "../BindingsIterator.h"

#include <vector>

using namespace planning;

const std::string ExistsExp::s_image = "exists";

bool ExistsExp::evaluate(const IClosedWorld* world, const Bindings* bindings) const
{
  //BindingsIterator bindingsIt(m_variables, bindings);
  //while (bindingsIt.nextBinding())
  //{
  //  const Bindings& currentBindings = bindingsIt.getCurrentBindings();
  //  if (m_body->evaluate(world, &currentBindings))
  //    return true;
  //}
  //return false;

  return _getGroundExp()->evaluate(world, bindings);
}

/// <summary>
/// Enumerates all the worlds within which this logical expression evaluates to true.
/// This method is used to support the goal modality expressions.
/// </summary>
/// <returns>All the worlds satisfying this logical expression.</returns>
void ExistsExp::enumerateSatisfyingWorlds(PartialWorldSet& worlds) const
{
  //const ILogicalExp* equivalentExp = _generateGroundExp();

  //equivalentExp->enumerateSatisfyingWorlds(worlds);
  //delete equivalentExp;

  return _getGroundExp()->enumerateSatisfyingWorlds(worlds);
}

ILogicalExp* ExistsExp::_generateGroundExp() const
{
  std::vector<const ILogicalExp*> exps;
  BindingsIterator bindingsIt(m_variables);
  while (bindingsIt.nextBinding())
  {
    const Bindings& currentBindings = bindingsIt.getCurrentBindings();
    exps.push_back(m_body->apply(&currentBindings));
  }
  return new OrExp(exps.size(), exps.begin(), exps.end());
}

void ExistsExp::_output(std::ostream& out) const
{
  QuantifiedExp<ILogicalExp>::_output(out); 
}

const IExp* ExistsExp::_internalApply(const Bindings* bindings) const
{
  return new ExistsExp(m_variables.begin(), m_variables.end(), m_body->apply(bindings));
}