from .manager.Normalization import Normalization
from framework import Guid

class InstanceCache:

	def __init__(self):

		self.next_inst_id = dict()
		self.next_inst_id[1] = 1

		self.inst_indices = dict()
		self.inst_guids = dict()

		self.dbids_gid = dict()

	def add_instance(self, inst_key, inst_gid : Guid):
		print ("registering instance key " + str(inst_key) + " = " + str(inst_gid))
		self.inst_guids[inst_key] = inst_gid
		self.inst_indices[inst_gid] = inst_key

		if not inst_key[0] in self.next_inst_id:
			print("inst_key " + str(inst_key[0]) + " not found in next_inst_id, initializing to 1")
			self.next_inst_id[inst_key[0]] = 1

		if inst_key[1] >= self.next_inst_id[inst_key[0]]:
			print ("incrementing next_inst_id [1$" + str(inst_key[0]) + "] = " + str(inst_key[1] + 1))
			self.next_inst_id[inst_key[0]] = inst_key[1] + 1
	
	def get_global_identifier(self, inst_key) -> Guid:
		if inst_key in self.inst_guids:
			return self.inst_guids[inst_key]
		return None

	def get_instance_key(self, inst_gid):
		if inst_gid in self.inst_indices:
			return self.inst_indices[inst_gid]
		return None
	
	def get_next_instance_id(self, class_index):
		if not class_index in self.next_inst_id:
			# this is the first instance of this class
			self.next_inst_id[class_index] = 1

		val = self.next_inst_id[class_index]
		self.next_inst_id[class_index] += 1
		return val
	
	def has_instance_by_global_identifier(self, gid):
		return gid in self.inst_indices

	def count(self) -> int:
		"""
		Returns the number of instances stored in this OMS.
		"""
		return len(self.inst_indices)
	
	def get_instance_global_identifers(self):
		return self.inst_guids

	def get_instance_keys(self):
		return self.inst_indices

	def set_database_id_by_global_identifier(self, gid : Guid, dbid):
		self.dbids_gid[Normalization.normalize_uuid(gid.get_value())] = dbid
		# self.dbids_idx[self.inst_indices[gid]] = dbid
	def get_database_id_by_global_identifier(self, gid : Guid):
		return self.dbids_gid[Normalization.normalize_uuid(gid.get_value())]
	
	def __len__(self):
		return len(self.inst_guids)