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

#include "../FlatListExp.h"
#include "../ILogicalExp.h"
#include "TrueExp.h"

#include <vector>

namespace planning
{
  /// <summary>
  /// This class represents a conjunction of logical expressions.
  /// </summary>
  class AndExp : public FlatListExp<ILogicalExp>, public ILogicalExp
  {
  public:
    /// <summary>
    /// Creates a new conjunction of logical expressions.
    /// </summary>
    /// <param name="exps">The logical expressions associated with the new conjunctive
    /// expression.</param>
    template <class Iterator>
    AndExp(size_t n, Iterator elementsBegin, Iterator elementsEnd)
      : FlatListExp<ILogicalExp>(n, s_image, elementsBegin, elementsEnd)
    {
      INITIALIZE_HASH_CODE();
    }

    AndExp(const ILogicalExp* exp1, const ILogicalExp* exp2)
      : FlatListExp<ILogicalExp>(s_image, exp1, exp2)
    {
      INITIALIZE_HASH_CODE();
    }

    template <class Iterator>
    static const ILogicalExp* instantiate(size_t n, Iterator elementsBegin, Iterator elementsEnd)
    {
      if (n == 0)
      {
        assert(elementsBegin == elementsEnd);
        return TrueExp::getInstance();
      }
      else if (n == 1)
      {
        assert(++Iterator(elementsBegin) == elementsEnd);
        return *elementsBegin;
      }
      else
      {
        return new AndExp(n, elementsBegin, elementsEnd);
      }
    }

    /// <summary>
    /// Evaluates this logical expression in the specified closed world.
    /// </summary>
    /// <param name="world">The evaluation world.</param>
    /// <param name="bindings">A set of variable bindings.</param>
    /// <returns>True, false, or undefined.</returns>
    virtual bool evaluate(const IClosedWorld* world, const Bindings* bindings) const;

    /// <summary>
    /// Enumerates all the worlds within which this logical expression evaluates to true.
    /// This method is used to support the goal modality expressions.
    /// </summary>
    /// <returns>All the worlds satisfying this logical expression.</returns>
    virtual void enumerateSatisfyingWorlds(PartialWorldSet& worlds) const;

  protected:
    virtual size_t _calculateHashCode() const
    {
      return CALCULATE_HASH_CODE(FlatListExp)
           + 886911075;
    }

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

  private:
    static const std::string s_image;

    //#region private class ContextData

    ///// <summary>
    ///// An instance of ContextData stores a world and a list of worlds satisfying a 
    ///// given element of the conjunctive formula.
    ///// </summary>
    //private class ContextData
    //{
    //  /// <summary>
    //  /// Creates a new ContextData instance with the specified world and and list of 
    //  /// satisfying worlds.
    //  /// </summary>
    //  /// <param name="world">The world to store in the new instance.</param>
    //  /// <param name="allWorlds">The list of worlds satysfing some logical expression.</param>
    //  public ContextData(PartialWorld world, IEnumerator<PartialWorld> allWorlds)
    //  {
    //    this.World = world;
    //    this.AllSatisfyingWorlds = allWorlds;
    //  }

    //  /// <summary>
    //  /// The world.
    //  /// </summary>
    //  public PartialWorld World { get; set; }
    //  /// <summary>
    //  /// The list of worlds satisfying some logical expression.
    //  /// </summary>
    //  public IEnumerator<PartialWorld> AllSatisfyingWorlds { get; set; }
    //}

    //#endregion

    ///// <summary>
    ///// Creates a new conjunction of logical expressions.
    ///// </summary>
    ///// <param name="exps">The logical expressions associated with the new conjunctive
    ///// expression.</param>
    //public AndExp(IEnumerable<ILogicalExp> exps)
    //  : base(exps.Cast<IConstraintExp>())
    //{
    //  System.Diagnostics.Debug.Assert(exps != null && !exps.ContainsNull());
    //}

    ///// <summary>
    ///// Evaluates this logical expression in the specified open world.
    ///// </summary>
    ///// <param name="world">The evaluation world.</param>
    ///// <param name="bindings">A set of variable bindings.</param>
    ///// <returns>True, false, undefined, or unknown.</returns>
    //public virtual FuzzyBool Evaluate(IReadOnlyOpenWorld world, ILocalBindings bindings)
    //{
    //  FuzzyBool value = FuzzyBool.True;
    //  foreach (ILogicalExp exp in this.m_expressions)
    //  {
    //    value = value & exp.Evaluate(world, bindings);
    //    if (!value)
    //      break;
    //  }
    //  return value;
    //}

    ///// <summary>
    ///// Evaluates this logical expression in the specified open world.
    ///// In addition to False, Undefined and Unknown also shortcircuit conjunctions.
    ///// In addition to True, Unknown also shortcircuits disjunctions.
    ///// </summary>
    ///// <param name="world">The evaluation world.</param>
    ///// <param name="bindings">A set of variable bindings.</param>
    ///// <returns>True, false, undefined, or unknown.</returns>
    //[TLPlan]
    //public virtual ShortCircuitFuzzyBool EvaluateWithImmediateShortCircuit(IReadOnlyOpenWorld world, ILocalBindings bindings)
    //{
    //  ShortCircuitFuzzyBool value = ShortCircuitFuzzyBool.True;
    //  foreach (ILogicalExp exp in this.m_expressions)
    //  {
    //    value = value & exp.EvaluateWithImmediateShortCircuit(world, bindings);
    //    if (!value)
    //      break;
    //  }
    //  return value;
    //}

    ///// <summary>
    ///// Simplifies this logical expression by evaluating its known expression parts.
    ///// </summary>
    ///// <param name="world">The evaluation world.</param>
    ///// <param name="bindings">A set of variable bindings.</param>
    ///// <returns>True, false, undefined, or the simplified expression.</returns>
    //public virtual LogicalValue Simplify(IReadOnlyOpenWorld world, ILocalBindings bindings)
    //{
    //  LogicalValue value = LogicalValue.True;
    //  foreach (ILogicalExp exp in this.m_expressions)
    //  {
    //    value = value & exp.Simplify(world, bindings);
    //    if (!value)
    //      break;
    //  }
    //  return value;
    //}

    ///// <summary>
    ///// Evaluates this logical expression in the specified closed world.
    ///// The bindings should not be modified by this call.
    ///// In addition to False, Undefined also shortcircuit conjunctions.
    ///// This function is used to evaluate defined formulas' body as is done in the
    ///// original TLPlan.
    ///// </summary>
    ///// <param name="world">The evaluation world.</param>
    ///// <param name="bindings">A set of variable bindings.</param>
    ///// <returns>True, false, or undefined.</returns>
    //[TLPlan]
    //public virtual ShortCircuitBool EvaluateWithImmediateShortCircuit(IReadOnlyClosedWorld world, ILocalBindings bindings)
    //{
    //  ShortCircuitBool value = ShortCircuitBool.True;
    //  foreach (ILogicalExp exp in this.m_expressions)
    //  {
    //    value = value & exp.EvaluateWithImmediateShortCircuit(world, bindings);
    //    if (!value)
    //      break;
    //  }
    //  return value;
    //}

    ///// <summary>
    ///// Enumerates all the worlds within which this logical expression evaluates to true.
    ///// The worlds satisfying a conjunctive expression correspond to all the legal permutations
    ///// of the worlds satisfying the individual logical expressions.
    ///// </summary>
    ///// <returns>All the worlds satisfying this logical expression.</returns>
    //public HashSet<PartialWorld> EnumerateAllSatisfyingWorlds()
    //{
    //  HashSet<PartialWorld> worlds = new HashSet<PartialWorld>();

    //  ContextData[] contexts = new ContextData[this.m_expressions.Count];
    //  PartialWorld currentContext = new PartialWorld();

    //  if (this.m_expressions.Count == 0)
    //  {
    //    worlds.Add(currentContext);
    //    return worlds;
    //  }

    //  for (int i = 0; i < this.m_expressions.Count; ++i)
    //  {
    //    IEnumerator<PartialWorld> enumerator = ((ILogicalExp)this.m_expressions[i]).EnumerateAllSatisfyingWorlds().GetEnumerator();
    //    contexts[i] = new ContextData(null, enumerator);
    //  }

    //  contexts[0].World = new PartialWorld();
    //  int currentIndex = 0;
    //  int lastIndex = this.m_expressions.Count - 1;
    //  while (currentIndex >= 0)
    //  {
    //    ContextData data = contexts[currentIndex];
    //    if (currentIndex == lastIndex)
    //    {
    //      while (data.AllSatisfyingWorlds.MoveNext())
    //      {
    //        PartialWorld newContext = data.World.Join(data.AllSatisfyingWorlds.Current);
    //        if (newContext != null)
    //          worlds.Add(newContext);
    //      }
    //      --currentIndex;
    //    }
    //    else
    //    {
    //      PartialWorld newContext = null;
    //      while (newContext == null && data.AllSatisfyingWorlds.MoveNext())
    //      {
    //        newContext = data.World.Join(data.AllSatisfyingWorlds.Current);
    //      }
    //      if (newContext == null)
    //      {
    //        if (--currentIndex < 0)
    //          break;
    //      }
    //      else
    //      {
    //        ++currentIndex;
    //        contexts[currentIndex].World = newContext;
    //        contexts[currentIndex].AllSatisfyingWorlds.Reset();
    //      }
    //    }
    //  }
    //  return worlds;
    //}
  };
}

#endif