<commit_before>""" Набор абстракций над базой данных """

from lib.commands import database


class DatabaseElement:
	""" Стандартный набор методов работы с объектами """
	def find(self, name):
		return self.xml_element.find(name)

	def get(self, *names):
		names = [self.find(n).text or "" for n in names]
		return names if len(names) > 1 else names[0]

	def set(self, name, value):
		self.find(name).text = value

	@property
	def exists(self):
		return self.xml_element is not None

	def getElement(self, id=None, name=None):
		""" Поиск элемента в базе данных """
		if id is not None:
			self._checkid(id)
			return database.getById(self.parent, id)
		elif name is not None:
			return database.getByName(self.parent, name)
		else:
			raise Exception("DatabaseElement: ты не указал id или имя")

	@staticmethod
	def _checkid(id):
		if str is not type(id) is not int:
			raise Exception("Неверный ID: Значение: {}, Тип: {}".format(id, type(id)))


class Guild(DatabaseElement):
	parent = "guilds"

	def __init__(self, id=None, name=None):
		self.xml_element = self.getElement(id, name)

	@property
	def heads(self):
		head = self.get("head")
		return self._getNonEmptyField(head)

	@property
	def vices(self):
		vice = self.get("vice")
		return self._getNonEmptyField(vice)

	@staticmethod
	def _getNonEmptyField(field):
		""" Почти пустое поле могло бы некорректно отобразиться """
		if field:
			return field.split(" ")
		else:
			return []

	def setPosition(self, player_id, position):
		""" Меняет статус игрока в гильдии

			Возможные аргументы:
			"player", "vice", "head"
		"""
		player_id = str(player_id)
		self._removePlayerFromOldPosition(player_id)
		if position != "player":
			self._putPlayerIntoNewPosition(player_id, position)

	def _removePlayerFromOldPosition(self, player_id):
		heads, vices = self.heads, self.vices
		if player_id in heads:
			heads.remove(player_id)
			self.set("head", " ".join(heads))
		elif player_id in self.vices:
			vices.remove(player_id)
			self.set("vice", " ".join(vices))

	def _putPlayerIntoNewPosition(self, player_id, position):
		if position == "head":
			element = self.find("head")
		elif position == "vice":
			element = self.find("head")
		element.text = "{} {}".format(element.text, player_id)


class Player(DatabaseElement):
	parent = "players"

	def __init__(self, id=None, name=None):
		self.xml_element = self.getElement(id, name)
		self.guild = self.getGuild()
		self.rank = self.getRank()
		self.name = name
		self.id = id

	def __repr__(self):
		""" Удобно в еженедельниках """
		if self.exists or (self.id and self.name):
			if self.exists:<commit_msg>[hot fix] a very dangerous bug that could make all vices heads<commit_after>""" Набор абстракций над базой данных """

from lib.commands import database


class DatabaseElement:
	""" Стандартный набор методов работы с объектами """
	def find(self, name):
		return self.xml_element.find(name)

	def get(self, *names):
		names = [self.find(n).text or "" for n in names]
		return names if len(names) > 1 else names[0]

	def set(self, name, value):
		self.find(name).text = value

	@property
	def exists(self):
		return self.xml_element is not None

	def getElement(self, id=None, name=None):
		""" Поиск элемента в базе данных """
		if id is not None:
			self._checkid(id)
			return database.getById(self.parent, id)
		elif name is not None:
			return database.getByName(self.parent, name)
		else:
			raise Exception("DatabaseElement: ты не указал id или имя")

	@staticmethod
	def _checkid(id):
		if str is not type(id) is not int:
			raise Exception("Неверный ID: Значение: {}, Тип: {}".format(id, type(id)))


class Guild(DatabaseElement):
	parent = "guilds"

	def __init__(self, id=None, name=None):
		self.xml_element = self.getElement(id, name)

	@property
	def heads(self):
		head = self.get("head")
		return self._getNonEmptyField(head)

	@property
	def vices(self):
		vice = self.get("vice")
		return self._getNonEmptyField(vice)

	@staticmethod
	def _getNonEmptyField(field):
		""" Почти пустое поле могло бы некорректно отобразиться """
		if field:
			return field.split(" ")
		else:
			return []

	def setPosition(self, player_id, position):
		""" Меняет статус игрока в гильдии

			Возможные аргументы:
			"player", "vice", "head"
		"""
		player_id = str(player_id)
		self._removePlayerFromOldPosition(player_id)
		if position != "player":
			self._putPlayerIntoNewPosition(player_id, position)

	def _removePlayerFromOldPosition(self, player_id):
		heads, vices = self.heads, self.vices
		if player_id in heads:
			heads.remove(player_id)
			self.set("head", " ".join(heads))
		elif player_id in self.vices:
			vices.remove(player_id)
			self.set("vice", " ".join(vices))

	def _putPlayerIntoNewPosition(self, player_id, position):
		if position == "head":
			element = self.find("head")
		elif position == "vice":
			element = self.find("vice")
		element.text = "{} {}".format(element.text, player_id)


class Player(DatabaseElement):
	parent = "players"

	def __init__(self, id=None, name=None):
		self.xml_element = self.getElement(id, name)
		self.guild = self.getGuild()
		self.rank = self.getRank()
		self.name = name
		self.id = id

	def __repr__(self):
		""" Удобно в еженедельниках """
		if self.exists or (self.id and self.name):
			if self.exists:
{'fraction_non_alphanumeric': 0.13159387407827566, 'fraction_numerical': 0.0007562866326337682, 'mean_word_length': 4.279441117764471, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 8}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1641010', 'n_tokens_mistral': 2064, 'n_tokens_neox': 1934, 'n_words': 490}