//
// 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 _NARITY_SUBSTRACT_H
#define _NARITY_SUBSTRACT_H

#include "FunctionExp.h"

#include <numeric>

namespace planning
{
  /// <summary>
  /// This class implements a n-ary substraction.
  /// </summary>
  class NAritySubstract : public FunctionExp
  {
  public:
    /// <summary>
    /// Creates a new subtraction function with the specified arguments.
    /// </summary>
    /// <param name="args">The arguments of the new subtraction function.</param>
    template <class Iterator>
    NAritySubstract(size_t n, Iterator argumentsBegin, Iterator argumentsEnd)
      : FunctionExp(n, s_image, argumentsBegin, argumentsEnd)
    {
      assert(m_arguments.size() >= 1);

      INITIALIZE_HASH_CODE();
    }

    NAritySubstract(const INumericExp* exp1, const INumericExp* exp2)
      : FunctionExp(s_image, exp1, exp2)
    {
      INITIALIZE_HASH_CODE();
    }

    /// <summary>
    /// Calculates the sum of all the arguments.
    /// </summary>
    /// <param name="args">The arguments to call the function with.</param>
    /// <returns>The sum of all the arguments.</returns>
    virtual double calculate(evaluated_argument_const_iterator begin,
                             evaluated_argument_const_iterator end) const
    {
      //const size_t arity = getArity();
      //if (arity == 1)
      //  return -arguments[0];
      //else
      //  return std::accumulate(arguments + 1, arguments + getArity(), 
      //                         arguments[0], std::minus<double>());

      return (getArity() == 1) ?
        -(*begin) :
        std::accumulate(begin + 1, end, *begin, std::minus<double>());
    }

  protected:
    virtual size_t _calculateHashCode() const
    {
      return CALCULATE_HASH_CODE(FunctionExp)
           + 4973489;
    }

    const IExp* _internalApply(const Bindings* bindings) const;

  private:
    static const std::string s_image;
  };
}

#endif