# Path: monotonic.py
# def monotonic_time():
#     """
#     Clock that cannot be set and represents monotonic time since some
#     unspecified starting point. The unit is a second.
#     """
#     t = timespec()
#     _clock_gettime(CLOCK_MONOTONIC, byref(t))
#     return t.tv_sec + t.tv_nsec / 1e9


from monotonic import monotonic_time
import logging
import eventlet
import redis
import struct
		
	def removeExpiredPeers(self):
		conn = self._getRedisConn()
		for info_hash in conn.sunion(Peers.SEEN_TORRENTS):
			self.log.info('Checking for expiry of peers @ %s',info_hash.encode('hex'))
			
			for peerNumber,lastSeenTime in conn.hgetall(info_hash + Peers.LAST_SEEN_SUFFIX).iteritems():
				currentTime = monotonic_time()
				
				if currentTime - float(lastSeenTime) >= self.peerExpirationPeriod:
					conn.hdel(info_hash,peerNumber)
					#if removing the peer causes the hash set to no longer
					#exist, then remove it from the set of observed torrents
					if not conn.exists(info_hash):
						conn.srem(Peers.SEEN_TORRENTS, info_hash)
					self.log.info('Expired peer')
		
	def updatePeer(self,info_hash,peer):
		peerNumber = self.getPeerNumber(peer)
		conn = self._getRedisConn()
		wasSeed = conn.hget(info_hash, peerNumber)
						
		if wasSeed == None:	
			wasSeed = False
		else:
			wasSeed = wasSeed == '1'
			
		isSeed = peer.left == 0
		isAdd = 1 == conn.hset(info_hash, peerNumber,'1' if isSeed else '0')
		

# Path: monotonic.py
# def monotonic_time():
#     """
#     Clock that cannot be set and represents monotonic time since some
#     unspecified starting point. The unit is a second.
#     """
#     t = timespec()
#     _clock_gettime(CLOCK_MONOTONIC, byref(t))
#     return t.tv_sec + t.tv_nsec / 1e9


# Path: peers.py
from monotonic import monotonic_time
import logging
import eventlet
import redis
import struct

		
	def removeExpiredPeers(self):
		conn = self._getRedisConn()
		for info_hash in conn.sunion(Peers.SEEN_TORRENTS):
			self.log.info('Checking for expiry of peers @ %s',info_hash.encode('hex'))
			
			for peerNumber,lastSeenTime in conn.hgetall(info_hash + Peers.LAST_SEEN_SUFFIX).iteritems():
				currentTime = monotonic_time()
				
				if currentTime - float(lastSeenTime) >= self.peerExpirationPeriod:
					conn.hdel(info_hash,peerNumber)
					#if removing the peer causes the hash set to no longer
					#exist, then remove it from the set of observed torrents
					if not conn.exists(info_hash):
						conn.srem(Peers.SEEN_TORRENTS, info_hash)
					self.log.info('Expired peer')
		
	def updatePeer(self,info_hash,peer):
		peerNumber = self.getPeerNumber(peer)
		conn = self._getRedisConn()
		wasSeed = conn.hget(info_hash, peerNumber)
						
		if wasSeed == None:	
			wasSeed = False
		else:
			wasSeed = wasSeed == '1'
			
		isSeed = peer.left == 0
		isAdd = 1 == conn.hset(info_hash, peerNumber,'1' if isSeed else '0')
		

		conn.hset(info_hash + Peers.LAST_SEEN_SUFFIX,peerNumber,monotonic_time())