//
// 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: Daniel Castonguay
// Project Manager: Froduald Kabanza
//

#include "stdafx.h"
#include "TemporalOrExp.h"
#include "../../UnaryFunctions.h"
#include "../../../World/IDurativeClosedWorld.h"

using namespace planning;

const std::string TemporalOrExp::s_image = "or";

ProgressionValue TemporalOrExp::progress(const IDurativeClosedWorld* world, const Bindings* bindings) const
{
  std::vector<const ITemporalExp*> suffix;
  suffix.reserve(m_elements.size());
  for (std::vector<const ITemporalExp*>::const_iterator it = m_elements.begin(); 
       it != m_elements.end();
       ++it)
  {
    ProgressionValue value = (*it)->progress(world, bindings);
    if (value.isTrue())
      return value;
    else if (!value.isFalse())
      suffix.push_back(value.getExp());
  }
  if (suffix.size() == 0)
    return ProgressionValue(false);
  else if (suffix.size() == 1)
    return ProgressionValue(suffix[0]);
  else
    return new TemporalOrExp(suffix.size(), suffix.begin(), suffix.end());
}

bool TemporalOrExp::evaluateIdle(const IDurativeClosedWorld* world, const Bindings* bindings) const
{
  for (const_iterator it = m_elements.begin(); 
       it != m_elements.end();
       ++it)
  {
    if ((*it)->evaluateIdle(world, bindings))
      return true;
  }
  return false;
}

const IExp* TemporalOrExp::_internalApply(const Bindings* bindings) const
{
  return new TemporalOrExp(m_elements.size(),
                           boost::transform_iterator<ApplyBindings<ITemporalExp>, const_iterator>(m_elements.begin(), bindings), 
                           boost::transform_iterator<ApplyBindings<ITemporalExp>, const_iterator>(m_elements.end(), bindings));
}