//
// 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 "BindingsIterator.h"

using namespace planning;

BindingsIterator::BindingsIterator(const std::vector<const ObjectParameterVariable*>& variables, 
                                   const Bindings* parentBindings)
  : m_variables(variables), m_currentObjects(variables.size()), 
    m_currentBindings(parentBindings), m_initialized(false)
{
  for (size_t i = 0; i < m_currentObjects.size(); ++i)
    m_currentObjects[i] = m_variables[i]->domainBegin();
}

BindingsIterator::BindingsIterator(const std::vector<const ObjectParameterVariable*>& variables)
  : m_variables(variables), m_currentObjects(variables.size()), 
    m_initialized(false)
{
  for (size_t i = 0; i < m_currentObjects.size(); ++i)
    m_currentObjects[i] = m_variables[i]->domainBegin();
}

bool BindingsIterator::nextBinding()
{
  if (!m_initialized)
  {
    m_initialized = true;
    for (size_t i = 0; i < m_currentObjects.size(); ++i)
    {
      ObjectParameterVariable::object_const_iterator it = m_variables[i]->domainBegin();
      if (it != m_variables[i]->domainEnd())
      {
        m_currentObjects[i] = it;
        m_currentBindings.bind(m_variables[i], *it);
      }
      else
      {
        return false;
      }
    }
    return m_currentObjects.size() > 0;
  }
  else
  {
    bool found = false;
    for (size_t i = m_currentObjects.size(); !found && i-- > 0; )
    {
      if (++m_currentObjects[i] != m_variables[i]->domainEnd())
      {
        m_currentBindings.bind(m_variables[i], *m_currentObjects[i]);
        found = true;
      }
      else
      {
        m_currentObjects[i] = m_variables[i]->domainBegin();
        m_currentBindings.bind(m_variables[i], *m_currentObjects[i]);
      }
    }
    return found;
  }
}

const Bindings& BindingsIterator::getCurrentBindings() const
{
  return m_currentBindings;
}