import cryptobox.plugins.base

RESERVED_USERS = [ "admin" ]

class user_manager(cryptobox.plugins.base.CryptoBoxPlugin):

	pluginCapabilities = [ "system" ]
	pluginVisibility = [ "preferences" ]
	requestAuth = True
	rank = 45

	def doAction(self, store=None, user=None, new_pw=None, new_pw2=None):
		import re
		adminDict = self.cbox.prefs.userDB["admins"]
		self.__cleanHDF()
		if store is None:
			pass
		elif store == "add_user":
			if (user is None) or (re.search(u'\W', user)):
				self.hdf["Data.Warning"] = "Plugins.user_manager.InvalidUserName"
			elif not new_pw:
				self.hdf["Data.Warning"] = "EmptyNewPassword"
			elif new_pw != new_pw2:
				self.hdf["Data.Warning"] = "DifferentPasswords"
			elif user in adminDict.keys():
				self.hdf["Data.Warning"] = "Plugins.user_manager.UserAlreadyExists"
			else:
				adminDict[user] = self.cbox.prefs.userDB.getDigest(new_pw)
				self.hdf["Data.Success"] = "Plugins.user_manager.UserAdded"
				try:
					self.cbox.prefs.userDB.write()
				except IOError:
					self.cbox.log.warn("failed to write user database")
		elif store == "change_password":
			if not new_pw:
				self.hdf["Data.Warning"] = "EmptyNewPassword"
			elif new_pw != new_pw2:
				self.hdf["Data.Warning"] = "DifferentPasswords"
			elif user in adminDict.keys():
				adminDict[user] = self.cbox.prefs.userDB.getDigest(new_pw)
				self.hdf["Data.Success"] = "Plugins.user_manager.PasswordChanged"
				try:
					self.cbox.prefs.userDB.write()
				except IOError:
					self.cbox.log.warn("failed to write user database")
			else:
				self.cbox.log.info("user_manager: invalid user choosen (%s)" % str(user))
		elif store == "del_user":
			if user in RESERVED_USERS:
				self.cbox.log.info("user_manager: tried to remove reserved user (%s)" % user)
			elif user in adminDict.keys():
				del adminDict[user]
				self.hdf["Data.Success"] = "Plugins.user_manager.UserAdded"
				try:
					self.cbox.prefs.userDB.write()
				except IOError:
					self.cbox.log.warn("failed to write user database")
			else:
				self.cbox.log.info("user_manager: tried to remove non-existing user (%s)" % str(user))
		else:
			self.cbox.log.info("user_manager: invalid value of 'store' (%s)" % store)
		self.__prepareHDF(adminDict)
		return "user_list"


	def getStatus(self):
		return "/".join(self.cbox.prefs.userDB["admins"].keys())


	def __cleanHDF(self):
		for key in self.hdf.keys():
			del self.hdf[key]


	def __prepareHDF(self, dict):
		## sort by name
		users = dict.keys()
		users.sort()
		## export all users
		for name in users:
			self.hdf[self.hdf_prefix + "Users." + name] = name

