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

#include "AlwaysExp.h"
#include "Composite/TemporalImplyExp.h"
#include "Composite/TemporalNotExp.h"
#include "TLPlan/WeakUntilExp.h"

namespace planning
{
  /// <summary>
  /// Represents a constraint expression which must be evaluated at the end of the trajectory.
  ///
  /// Generates and returns the compound constraint expression equivalent to this expression.
  /// In this case, <c>(at-most-once a) = (always (imply a (weak-until a (always ¬a))))</c>.
  /// </summary>
  /// <remarks>
  /// This equivalence was adapated from the "Plan Constraints and Preferences in PDDL3" document,
  /// written by Alfonso Gerevini and Derek Long. The original definition was
  /// <c>(at-most-once a) = (always (imply a (until a (always ¬a))))</c>; the problem with this definition is
  /// that once the predicate <c>a</c> becomes true, it has to become false for this to progress to true.
  /// </remarks>
  /// <returns>An equivalent constraint expression to this expression.</returns>
  /// <seealso cref="AlwaysExp"/>
  /// <seealso cref="ImplyConstraintExp"/>
  /// <seealso cref="UntilExp"/>
  /// <seealso cref="NotConstraintExp"/>
  class AtMostOnceExp : public AlwaysExp
  {
  public:
    AtMostOnceExp(const ITemporalExp *exp)
      : AlwaysExp(new TemporalImplyExp(m_exp, new WeakUntilExp(m_exp, new AlwaysExp(new TemporalNotExp(m_exp))))), m_exp(exp)
    {
      assert(m_exp != NULL);

      m_exp->acquire(this);

      INITIALIZE_HASH_CODE();
    }

    ~AtMostOnceExp()
    {
      m_exp->release(this);
    }

  protected:
    virtual void _output(std::ostream& out) const;

    virtual size_t _calculateHashCode() const
    {
      return 3 * m_exp->getHashCode()
           + 794099;
    }

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

    virtual int _internalCompareTo(const IExp& other) const;

  private:
    const ITemporalExp* m_exp;
  };
}

#endif