////////////////////////////////////////////////////////////////////////////////
// Mercury and Colyseus Software Distribution 
// 
// Copyright (C) 2004-2005 Ashwin Bharambe (ashu@cs.cmu.edu)
//               2004-2005 Jeffrey Pang    (jeffpang@cs.cmu.edu)
//                    2004 Mukesh Agrawal  (mukesh@cs.cmu.edu)
// 
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2, or (at
// your option) any later version.
// 
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
////////////////////////////////////////////////////////////////////////////////

/**************************************************************************
  Event.h

  Class representing a publication.

  $Id: Event.h 2382 2005-11-03 22:54:59Z ashu $

***************************************************************************/


#ifndef __EVENT__H
#define __EVENT__H

#include <string>
#include <map>
#include <mercury/common.h>
#include <mercury/Tuple.h>
#include <mercury/Constraint.h>
#include <hash_map.h>
#include <mercury/AutoSerializer.h>
#include <util/refcnt.h>

class Interest;

typedef byte EventType;
extern EventType    PUB_MERC, PUB_POINT;
void RegisterEventTypes();

/**
 * A publication passed to Mercury. GObjects produce one of these to indicate
 * their "location" in the world, which is matched to <code>Interest</code>s
 * generated by remote objects. 
 *
 * All events are now "range" events and abstract interfaces for 
 * allowing app-specific optimizations.
 */
class Event : public virtual Serializable {
 protected:
    bool    m_Matched;      // "true" once the rendezvous point has matched this event
    uint32  m_LifeTime; 

    uint32  m_Nonce;        // Measurement variable

    TimeVal m_DeathTime;    // Not serialized. Used by MercuryNode; ideally, MercuryNode should 
    // maintain another data structure which contains Event and this info

    DECLARE_BASE_TYPE(Event);
 public:
    uint32  m_TriggerCount; // DEBUG : Jeff [10/7] - number times this pub was triggered

    Event ();
    Event (Packet *pkt);
    virtual ~Event() {}

    void SetMatched() { m_Matched = true; }
    bool IsMatched() const { return m_Matched; }

    void SetLifeTime(uint32 lifetime) { m_LifeTime = lifetime; }
    uint32 GetLifeTime() const { return m_LifeTime; }

    ///// MEASUREMENT (see ObjectLogs.h)
    void    SetNonce(uint32 nonce) { m_Nonce = nonce; }
    uint32  GetNonce() { return m_Nonce; }

    // used by MercuryNode ONLY to manage this as softstate
    void SetDeathTime(TimeVal time) { m_DeathTime = time; }
    const TimeVal& GetDeathTime() const { return m_DeathTime; }

    /// Methods all event classes MUST override...
    /**
     * Returns the number of constraints in the event.
     **/
    virtual int GetNumConstraints () = 0;

    /**
     * Returns the 'i'th constraint in the event.
     **/
    virtual Constraint *GetConstraint (int index) = 0;

    /**
     * this method is used (ultimately) as the comparator in 
     * the Event hashtable used for publication overwriting
     **/
    virtual bool LessThan (const Event *oe) const {
	return GetType () < oe->GetType () || (this < oe);
    }

    /**
     * This is to be used in conjunction with the above method
     * The method decides whether the newer event overrides the 
     * earlier stored trigger.
     **/
    virtual bool OverwriteEvent (Event *oe) {
	return true;
    }

    /**
     * Print itself to the ostream
     **/
    virtual ostream& Print (ostream& os) const = 0;

    /// Methods of the Serializable interface...

    virtual void   Serialize(Packet *pkt);
    virtual uint32 GetLength();
    virtual void   Print(FILE *stream);

    /// misc

    virtual const char *TypeString() { return "EVENT"; }

    Constraint *GetConstraintByAttr (int attr_index);
};

ostream& operator<<(ostream& out, const Event *evt);
ostream& operator<<(ostream& out, const Event &evt);

/**
 * An implementation of the Event interface which should be 
 * sufficient for many apps. Mercury however uses only the 
 * interface provided by Event for taking all routing decisions.
 **/
class MercuryEvent : public Event {
 protected:
    ConstraintVec   m_Constraints;
    DECLARE_TYPE(Event, MercuryEvent);
 public:
    MercuryEvent() {}
    MercuryEvent(Packet *pkt);

    virtual int GetNumConstraints () {
	return (int) m_Constraints.size ();
    }

    virtual Constraint *GetConstraint (int index) {
	ASSERT (index < (int) m_Constraints.size ());
	return &m_Constraints [index];
    }

    virtual ostream& Print (ostream& os) const;

    //////////////////////////////////////////////////////////////////////////
    // if we are a range publication
    virtual void AddConstraint (Constraint& c);

    virtual void Serialize(Packet *pkt);
    virtual uint32 GetLength();
    virtual void Print(FILE *stream);

    virtual const char *TypeString() { return "RANGE_EVENT"; }

    /// other classes access constraints using this iterator 
    /// so that my implementation details are hidden. 

    class iterator;
    friend class iterator;
    class iterator {
	MercuryEvent&       re;
	ConstraintVecIter it;
    public:
	iterator (MercuryEvent& re) : re (re), it (re.m_Constraints.begin()) {}
	iterator (MercuryEvent& re, bool) 
	    : re (re), it (re.m_Constraints.end ()) {}

	iterator(const iterator& o)
	    : re (o.re), it (o.it) {}

	Constraint *operator*() const { return &*it; }

	iterator& operator++() { // Prefix
	    ASSERT (it != re.m_Constraints.end()); 
	    it++;
	    return *this;
	}
	iterator& operator++(int) { // Postfix
	    return operator++();
	}

	bool operator== (const iterator& o) const {
	    return it == o.it;
	}
	bool operator!= (const iterator& o) const {
	    return it != o.it;
	}
	friend ostream& 
	    operator<<(ostream& os, const iterator& it) {
	    return os << *it;
	}
    };

    iterator begin() const { return iterator((MercuryEvent& ) *this); }
    iterator end() const { return iterator((MercuryEvent& ) *this, true);  }
};

/**
 * Specialized events in which each range is a single
 * point. (min == max)
 **/
class PointEvent : public MercuryEvent
{
 protected:
    DECLARE_TYPE(Event, PointEvent);
 public:
    PointEvent() : MercuryEvent () {}
    PointEvent(Packet *pkt) : MercuryEvent (pkt) {}

    virtual ~PointEvent() {}

    virtual ostream& Print (ostream& out) const;

    virtual void AddConstraint (Constraint& c);
    void AddTuple(Tuple& t);
    Value *GetValueByAttr (int attr_index);

    virtual void   Serialize(Packet *pkt) { MercuryEvent::Serialize (pkt); }
    virtual uint32 GetLength() { return MercuryEvent::GetLength (); }
    virtual void   Print(FILE *stream) { MercuryEvent::Print (stream); }

    virtual const char *TypeString() { return "POINT_EVENT"; }
};

#if 0
class SamplerEvent : public PointEvent {
    uint32 m_MetricID;

 protected:
    DECLARE_TYPE(Event, SamplerEvent);
 public:
    SamplerEvent (uint32 mid) : PointEvent (), m_MetricID (mid) {}
    SamplerEvent(Packet *pkt);

    virtual ostream& Print (ostream& out) const;

    virtual void   Serialize(Packet *pkt);
    virtual uint32 GetLength();
    virtual void   Print(FILE *stream);

    virtual bool OnRendezvousReceive(MemberHub *h, MsgPublication *pmsg);
    virtual const char *TypeString() { return "SAMPLER_EVENT"; }
};

class NeighborRequestEvent : public PointEvent {
    int    m_Epoch;
 protected:
    DECLARE_TYPE(Event, NeighborRequestEvent);

 public:
    NeighborRequestEvent(int epoch) : PointEvent(), m_Epoch(epoch) {}
    NeighborRequestEvent(Packet *pkt);

    virtual void Serialize(Packet *pkt);
    virtual uint32 GetLength();
    virtual void Print(FILE *stream);

    int GetEpoch() const { return m_Epoch; }
    virtual ostream& Print (ostream& os) const;
    virtual bool OnRendezvousReceive(MemberHub *h, MsgPublication *pmsg);

    virtual const char *TypeString() { return "NEIGHBOR_REQUEST_EVENT"; }
};
#endif

#endif // __EVENT__H
// vim: set sw=4 sts=4 ts=8 noet: 
// Local Variables:
// Mode: c++
// c-basic-offset: 4
// tab-width: 8
// indent-tabs-mode: t
// End:
