//
// 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
//

#ifndef _NUMERIC_EXCEPTION_H
#define _NUMERIC_EXCEPTION_H

#include "../Exp/Numeric/FunctionExp.h"
#include "../Exp/Formula/Described/NumericFluentApplication.h"
#include "../Utils/Utils.h"

#include <stdexcept>

namespace planning
{
  /// <summary>
  /// A NumericException is thrown if an attempt is made to perform an illegal
  /// arithmetic operation (like a division by zero).
  /// </summary>
  class NumericException : public std::domain_error
  {
  public:
    /// <summary>
    /// Creates a new NumericException with a specific cause and arguments.
    /// </summary>
    /// <param name="cause">The function that caused the exception.</param>
    /// <param name="arguments">The arguments the function was evaluated with.</param>
    template <class Iterator>
    NumericException(const FunctionExp* cause, Iterator argumentsBegin, Iterator argumentsEnd)
      : std::domain_error(buildErrorMessage(cause, argumentsBegin, argumentsEnd))
    {
    }

    NumericException(const NumericFluentApplication* fluent, double value)
      : std::domain_error(buildErrorMessage(fluent, value))
    {
    }

    NumericException()
      : std::domain_error("An illegal numeric operation has been performed")
    {
    }

  private:

    template <class Iterator>
    static std::string buildErrorMessage(const FunctionExp* cause, 
                                         Iterator argumentsBegin, 
                                         Iterator argumentsEnd)
    {
      std::string error = toString(cause);
      error.append(" was called with (");
      for (Iterator current = argumentsBegin; current != argumentsEnd; ++current)
      {
        if (current != argumentsBegin)
          error.append(", ");
        error.append(stringify(*current));
      }
      error.append(")");
      return error;
    }

    static std::string buildErrorMessage(const NumericFluentApplication* fluent, 
                                         double value)
    {
      std::string error = "An attempt was made to set the value '";
      error.append(stringify(value));
      error.append("' to the fluent '");
      error.append(toString(fluent));
      error.append("'");

      return error;
    }
  };
}

#endif