#Thanks to: https://stackoverflow.com/a/19431276
import collections
from blist import sorteddict

class TwoWayPriorityQueue(collections.MutableMapping):

	def __init__(self, data):
		self._dict = {}
		self._sorted = sorteddict()
		self.update(data)

	def __getitem__(self, key):
		return self._dict[key]

	def __setitem__(self, key, value):
		# remove old value from sorted dictionary
		if key in self._dict:
			self.__delitem__(key)
		# update structure with new value
		self._dict[key] = value
		try:
			keys = self._sorted[value]
		except KeyError:
			self._sorted[value] = set([key])
		else:
			keys.add(key)	#to handle having more than 1 keys with similar values
		

	def __delitem__(self, key):
		value = self._dict.pop(key)
		keys = self._sorted[value]
		keys.remove(key)
		if not keys:
			del self._sorted[value]

	def __iter__(self):
		try:		
			for value, keys in self._sorted.items():
				for key in keys:
					yield key
		except Exception:
			return;
	
	def __len__(self):
		return len(self._dict)

	def next_best(self):
		for value, keys in self._sorted.items():
			for key in keys:
				return key;

	def removeEntry(self,key):
		value = self._dict.pop(key)
		keys = self._sorted[value]
		keys.remove(key)
		if not keys:
			del self._sorted[value]
				
	def hasMore(self):
		return len(self._dict)>0;




'''
d={};
d[(1,2,1)]=1
d[(1,2,2)]=2
d[(2,3,1)]=3
d[(2,3,2)]=4
x = TwoWayPriorityQueue(d)
print("-----------------")
print (list(x.items()))
x[(1,2,1)] = 10
print("-----------------")
print (list(x.items()))
x[(2,3,2)] = -55
print("-----------------")
print (list(x.items()))
print(len(x.items()));
print("-----------------")
x[(2,3,100)] = -155
print (list(x.items()))
print(len(x.items()));
print("-----------------")
'''
