//
// 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 "Bindings.h"
#include "../Exception/BindingException.h"
#include "Term/ObjectParameterVariable.h"

using namespace planning;

const Bindings Bindings::s_emptyBindings = Bindings();

/// <summary>
/// Creates a new empty set of local/parameter bindings.
/// </summary>
Bindings::Bindings()
  : m_previous(0)
{
}

/// <summary>
/// Creates a new empty set of local/parameter bindings with a specified parent set.
/// </summary>
/// <param name="previous">The parent set of parameter bindings.</param>
Bindings::Bindings(const Bindings* previous)
  : m_previous(previous)
{
}

const Bindings* Bindings::emptyBindings()
{
  return &s_emptyBindings;
}

bool Bindings::tryGetBinding(const ObjectParameterVariable* var, const Object*& value) const
{
  std::map<const ObjectParameterVariable*, const Object*>::const_iterator it = 
    m_mapping.find(var);

  if (it != m_mapping.end())
  {
    value = it->second;
    return true;
  }
  else if (m_previous != 0)
  {
    return m_previous->tryGetBinding(var, value);
  }
  else
  {
    return false;
  }
}

const Object* Bindings::getBinding(const ObjectParameterVariable* var) const
{
  std::map<const ObjectParameterVariable*, const Object*>::const_iterator it = 
    m_mapping.find(var);

  if (it != m_mapping.end())
  {
    return it->second;
  }
  else if (m_previous != 0)
  {
    return m_previous->getBinding(var);
  }
  else
  {
    throw BindingException(var);
  }
}

void Bindings::bind(const ObjectParameterVariable* var, const Object* value)
{
  m_mapping[var] = value;

  //std::pair<std::map<const ObjectParameterVariable*, const Object*>::iterator, bool> p =
  //  m_mapping.insert(std::make_pair(var, value));

  //if (!p.second)
  //{
  //  p.first->second = value;
  //}
}
