/*
 * Copyright (C) 2008 The Trustees of Columbia University in the City of New York. 
 * All rights reserved.
 *
 * See the file LICENSE included in this distribution for details.
 */

#ifndef _BAMBOOPEER_H
#define _BAMBOOPEER_H

#include "peer.h"

#ifndef _WENGO
#include "types.h"
#include "msgheader.h"
#include "bigint.h"
#include "bamboortable.h"
#endif

#ifdef _WENGO
#include "p2pp/msg/msgheader.h"
#include "p2pp/bigint/bigint.h"
#include "p2pp/table/bamboortable.h"
#include "p2pp/common/types.h"
#endif

//class Transaction;

class BambooPeer : public Peer {
  
 private:
  BambooRTable* m_pBRT;
  BambooNTable* m_pBNT;
  uint32 m_PushPull, m_GlobalTuning, m_LocalTuning;
 private:

  int32 OnACK(char* pchIP, int32 port, transtype tt);
  int32 OnRequest(char* pchIP, int32 port, transtype tt);
  int32 OnResponse(char* pchIP, int32 port, transtype tt);
  int32 OnIndication(char* pchIP, int32 port, transtype tt);
  
  void OnTransactionTimeout(Transaction* pobjTrans);


  uint32 getNextHop(uchar* peerid, uint32 len, struct peerinfo& stP);
  int32 GlobalTuning(int32 l, int32 d, void* (*callback)(void*, int32));
  //void* GlobalTuningOnPLookup(void* pN, int32 respcode);

 protected:
  //for timer management
  struct timeval m_tPushPull;
  struct timeval m_tGlobalTuning;
  struct timeval m_tLocalTuning;

  void setPushPullTimer();
  int32 isPushPullExpired();
  void setGlobalTuningTimer();
  int32 isGlobalTuningExpired();
  void setLocalTuningTimer();
  int32 isLocalTuningExpired();

 public:
  BambooPeer();
  ~BambooPeer();

  void Initialize();
  void OnTimer();
  int32 OnReceive(uchar* buf, int len, char* pchIP, int32 port, transtype tt);

  int32 Insert (char8* pchKey, int32 klen, char8* pchValue, int32 vlen, void* (*)(void*, int32), void* pApp);
  int32 RLookup (char8* pchKey, int32 klen, void* (*)(void*, int32), void* pApp, void* pConference );
  int32 PLookup (char8* pchKey, int32 klen, void* (*)(void*, int32), void* pApp, void* pConference);


  //Debugging functions for checking the local state
  void ShowRT();
  void ShowNT();
  void ShowRO();

  //Insert in routing or neighbor table
  int32 Insert(struct peerinfo& stP, int32 updateKA);
  int32 Insert(list<peerinfo>& lstP, int32 updateKA);
  int32 Insert(struct peerinfo& stP, int32 updateKA, uint16 stunPort);

  friend void* GlobalTuningOnLookupPeer(void* pN, int32 respcode);

};

#endif  
