package at.oefai.aaa.agent.jam;

import java.io.Serializable;

import at.oefai.aaa.agent.jam.types.Binding;

/**
 * A World Model entry.
 * @author Marc Huber
 * @author Jaeho Lee
 */
public class WorldModelRelation extends Relation implements Serializable {
    private static final int MAX_CYCLE_COUNT = Integer.MAX_VALUE;
    private int cycleCount = 0; // number of cycles this relation was present
    private final boolean perceptionTag; // true for all perceptions
    private boolean assertedTag = false; // true while part of a worldmodel

    /** Constructor based on an existing relation. */
    public WorldModelRelation(final Relation rel) {
        this(rel, false);
    }

    /** Constructor based on an existing relation specifying if it is a perception. */
    public WorldModelRelation(final Relation rel, final boolean isPerceived) {
        super(rel, (Binding) null);
        this.perceptionTag = isPerceived;
    }

    public final boolean isNew() { return this.cycleCount == 0; }

    public final boolean isPerception() { return this.perceptionTag; }

    public final boolean isAsserted() { return this.assertedTag; }

    public final void setAsserted(final boolean asstag) { this.assertedTag = asstag; }

    public final void advanceAge() { if (this.cycleCount < MAX_CYCLE_COUNT) ++this.cycleCount; }

    public final int getAge() { return this.cycleCount; }

    /** Return whether a match can be found for the specified relation and variable binding.
     * also checks for the usage of new entries
     */
    public final boolean matchRelation(final Relation pattRelation, final Binding pattBinding) {
        if (unify(pattRelation, pattBinding, this, (Binding) null)) {
            if (pattBinding != null) {
                pattBinding.checkNewWMBinding(isNew());
            }
            return true;
        }
        return false;
    }

}

