# Copyright (c) 2022, JINGROW and Contributors
# License: MIT. See LICENSE

# Tree (Hierarchical) Nested Set Model (nsm)
#
# To use the nested set model,
# use the following pattern
# 1. name your parent field as "parent_item_group" if not have a property nsm_parent_field as your field name in the document class
# 2. have a field called "old_parent" in your fields list - this identifies whether the parent has been changed
# 3. call update_nsm(pg_obj) in the on_upate method

# ------------------------------------------
from collections.abc import Iterator

import jingrow
from jingrow import _
from jingrow.model.page import Page
from jingrow.query_builder import Order
from jingrow.query_builder.functions import Coalesce, Max
from jingrow.query_builder.terms import SubQuery
from jingrow.query_builder.utils import PageType


class NestedSetRecursionError(jingrow.ValidationError):
	pass


class NestedSetMultipleRootsError(jingrow.ValidationError):
	pass


class NestedSetChildExistsError(jingrow.ValidationError):
	pass


class NestedSetInvalidMergeError(jingrow.ValidationError):
	pass


# called in the on_update method
def update_nsm(pg):
	# get fields, data from the PageType
	old_parent_field = "old_parent"
	parent_field = "parent_" + jingrow.scrub(pg.pagetype)

	if hasattr(pg, "nsm_parent_field"):
		parent_field = pg.nsm_parent_field
	if hasattr(pg, "nsm_oldparent_field"):
		old_parent_field = pg.nsm_oldparent_field

	parent, old_parent = pg.get(parent_field) or None, pg.get(old_parent_field) or None

	# has parent changed (?) or parent is None (root)
	if not pg.lft and not pg.rgt:
		update_add_node(pg, parent or "", parent_field)
	elif old_parent != parent:
		update_move_node(pg, parent_field)

	# set old parent
	pg.set(old_parent_field, parent)
	jingrow.db.set_value(pg.pagetype, pg.name, old_parent_field, parent or "", update_modified=False)
	jingrow.clear_document_cache(pg.pagetype)

	pg.reload()


def update_add_node(pg, parent, parent_field):
	"""
	insert a new node
	"""
	pagetype = pg.pagetype
	name = pg.name
	Table = PageType(pagetype)

	# get the last sibling of the parent
	if parent:
		left, right = jingrow.db.get_value(pagetype, {"name": parent}, ["lft", "rgt"], for_update=True)
		validate_loop(pg.pagetype, pg.name, left, right)
	else:  # root
		right = (
			jingrow.qb.from_(Table)
			.select(Coalesce(Max(Table.rgt), 0) + 1)
			.where(Coalesce(Table[parent_field], "") == "")
			.run(pluck=True)[0]
		)

	right = right or 1

	# update all on the right
	jingrow.qb.update(Table).set(Table.rgt, Table.rgt + 2).where(Table.rgt >= right).run()
	jingrow.qb.update(Table).set(Table.lft, Table.lft + 2).where(Table.lft >= right).run()

	if jingrow.qb.from_(Table).select("*").where((Table.lft == right) | (Table.rgt == right + 1)).run():
		jingrow.throw(_("Nested set error. Please contact the Administrator."))

	# update index of new node
	jingrow.qb.update(Table).set(Table.lft, right).set(Table.rgt, right + 1).where(Table.name == name).run()
	return right


def update_move_node(pg: Page, parent_field: str):
	parent: str = pg.get(parent_field)
	Table = PageType(pg.pagetype)

	if parent:
		new_parent = (
			jingrow.qb.from_(Table)
			.select(Table.lft, Table.rgt)
			.where(Table.name == parent)
			.for_update()
			.run(as_dict=True)[0]
		)

		validate_loop(pg.pagetype, pg.name, new_parent.lft, new_parent.rgt)

	# move to dark side
	jingrow.qb.update(Table).set(Table.lft, -Table.lft).set(Table.rgt, -Table.rgt).where(
		(Table.lft >= pg.lft) & (Table.rgt <= pg.rgt)
	).run()

	# shift left
	diff = pg.rgt - pg.lft + 1
	jingrow.qb.update(Table).set(Table.lft, Table.lft - diff).set(Table.rgt, Table.rgt - diff).where(
		Table.lft > pg.rgt
	).run()

	# shift left rgts of ancestors whose only rgts must shift
	jingrow.qb.update(Table).set(Table.rgt, Table.rgt - diff).where(
		(Table.lft < pg.lft) & (Table.rgt > pg.rgt)
	).run()

	if parent:
		# re-query value due to computation above
		new_parent = (
			jingrow.qb.from_(Table)
			.select(Table.lft, Table.rgt)
			.where(Table.name == parent)
			.for_update()
			.run(as_dict=True)[0]
		)

		# set parent lft, rgt
		jingrow.qb.update(Table).set(Table.rgt, Table.rgt + diff).where(Table.name == parent).run()

		# shift right at new parent
		jingrow.qb.update(Table).set(Table.lft, Table.lft + diff).set(Table.rgt, Table.rgt + diff).where(
			Table.lft > new_parent.rgt
		).run()

		# shift right rgts of ancestors whose only rgts must shift
		jingrow.qb.update(Table).set(Table.rgt, Table.rgt + diff).where(
			(Table.lft < new_parent.lft) & (Table.rgt > new_parent.rgt)
		).run()

		new_diff = new_parent.rgt - pg.lft
	else:
		# new root
		max_rgt = jingrow.qb.from_(Table).select(Max(Table.rgt)).run(pluck=True)[0]
		new_diff = max_rgt + 1 - pg.lft

	# bring back from dark side
	jingrow.qb.update(Table).set(Table.lft, -Table.lft + new_diff).set(Table.rgt, -Table.rgt + new_diff).where(
		Table.lft < 0
	).run()


@jingrow.whitelist()
def rebuild_tree(pagetype, parent_field=None):
	"""Call rebuild_node for all root nodes.

	The `parent_field` parameter is ignored and will be removed in v16+ (kept for backward compatibility).
	"""

	# Check for perm if called from client-side
	if jingrow.request and jingrow.local.form_dict.cmd == "rebuild_tree":
		jingrow.only_for("System Manager")

	meta = jingrow.get_meta(pagetype)
	if not meta.has_field("lft") or not meta.has_field("rgt"):
		jingrow.throw(
			_("Rebuilding of tree is not supported for {}").format(jingrow.bold(pagetype)),
			title=_("Invalid Action"),
		)

	parent_field = meta.nsm_parent_field or f"parent_{jingrow.scrub(pagetype)}"

	# get all roots
	right = 1
	table = PageType(pagetype)
	column = getattr(table, parent_field)
	result = (
		jingrow.qb.from_(table)
		.where((column == "") | (column.isnull()))
		.orderby(table.name, order=Order.asc)
		.select(table.name)
	).run()

	jingrow.db.auto_commit_on_many_writes = 1

	for r in result:
		right = rebuild_node(pagetype, r[0], right, parent_field)

	jingrow.db.auto_commit_on_many_writes = 0


def rebuild_node(pagetype, parent, left, parent_field):
	"""
	reset lft, rgt and recursive call for all children
	"""
	# the right value of this node is the left value + 1
	right = left + 1

	# get all children of this node
	table = PageType(pagetype)
	column = getattr(table, parent_field)

	result = (jingrow.qb.from_(table).where(column == parent).select(table.name)).run()

	for r in result:
		right = rebuild_node(pagetype, r[0], right, parent_field)

	# we've got the left value, and now that we've processed
	# the children of this node we also know the right value
	jingrow.db.set_value(pagetype, parent, {"lft": left, "rgt": right}, update_modified=False)

	# return the right value of this node + 1
	return right + 1


def validate_loop(pagetype, name, lft, rgt):
	"""check if item not an ancestor (loop)"""
	if name in jingrow.get_all(pagetype, filters={"lft": ["<=", lft], "rgt": [">=", rgt]}, pluck="name"):
		jingrow.throw(_("Item cannot be added to its own descendants"), NestedSetRecursionError)


def remove_subtree(pagetype: str, name: str, throw=True):
	"""Remove pg and all its children.

	WARN: This does not run any controller hooks for deletion and deletes them with raw SQL query.
	"""
	jingrow.has_permission(pagetype, ptype="delete", throw=throw)

	# Determine the `lft` and `rgt` of the subtree to be removed.
	lft, rgt = jingrow.db.get_value(pagetype, name, ["lft", "rgt"])

	# Delete the subtree by removing all nodes whose values for `lft` and `rgt`
	# lie within above values or match them.
	jingrow.db.delete(pagetype, {"lft": (">=", lft), "rgt": ("<=", rgt)})

	# The width of the subtree is calculated as the difference between `rgt` and
	# `lft` plus 1.
	width = rgt - lft + 1

	# All `lft` and `rgt` values, that are greater than the `rgt` of the removed
	# subtree, must be reduced by the width of the subtree.
	table = jingrow.qb.PageType(pagetype)
	jingrow.qb.update(table).set(table.lft, table.lft - width).where(table.lft > rgt).run()
	jingrow.qb.update(table).set(table.rgt, table.rgt - width).where(table.rgt > rgt).run()

	jingrow.clear_document_cache(pagetype)


class NestedSet(Page):
	def __setup__(self):
		if self.meta.get("nsm_parent_field"):
			self.nsm_parent_field = self.meta.nsm_parent_field

	def on_update(self):
		update_nsm(self)
		self.validate_ledger()

	def on_trash(self, allow_root_deletion=False):
		"""
		Runs on deletion of a document/node

		:param allow_root_deletion: used for allowing root document deletion (DEPRECATED)
		"""

		if not getattr(self, "nsm_parent_field", None):
			self.nsm_parent_field = jingrow.scrub(self.pagetype) + "_parent"

		parent = self.get(self.nsm_parent_field)
		if not parent and not getattr(self, "allow_root_deletion", True):
			jingrow.throw(_("Root {0} cannot be deleted").format(_(self.pagetype)))

		# cannot delete non-empty group
		self.validate_if_child_exists()

		self.set(self.nsm_parent_field, "")

		try:
			update_nsm(self)
		except jingrow.DoesNotExistError:
			if self.flags.on_rollback:
				jingrow.clear_last_message()
			else:
				raise

	def validate_if_child_exists(self):
		has_children = jingrow.db.count(self.pagetype, filters={self.nsm_parent_field: self.name})
		if has_children:
			jingrow.throw(
				_("Cannot delete {0} as it has child nodes").format(self.name), NestedSetChildExistsError
			)

	def before_rename(self, olddn, newdn, merge=False, group_fname="is_group"):
		if merge and hasattr(self, group_fname):
			is_group = jingrow.db.get_value(self.pagetype, newdn, group_fname)
			if self.get(group_fname) != is_group:
				jingrow.throw(
					_("Merging is only possible between Group-to-Group or Leaf Node-to-Leaf Node"),
					NestedSetInvalidMergeError,
				)

	def after_rename(self, olddn, newdn, merge=False):
		if not self.nsm_parent_field:
			parent_field = "parent_" + self.pagetype.replace(" ", "_").lower()
		else:
			parent_field = self.nsm_parent_field

		# set old_parent for children
		jingrow.db.set_value(
			self.pagetype,
			{parent_field: newdn},
			{"old_parent": newdn},
			update_modified=False,
		)

		if merge:
			rebuild_tree(self.pagetype, parent_field)

	def validate_one_root(self):
		if not self.get(self.nsm_parent_field):
			if self.get_root_node_count() > 1:
				jingrow.throw(_("""Multiple root nodes not allowed."""), NestedSetMultipleRootsError)

	def get_root_node_count(self):
		return jingrow.db.count(self.pagetype, {self.nsm_parent_field: ""})

	def validate_ledger(self, group_identifier="is_group"):
		if hasattr(self, group_identifier) and not bool(self.get(group_identifier)):
			if jingrow.get_all(self.pagetype, {self.nsm_parent_field: self.name, "pagestatus": ("!=", 2)}):
				jingrow.throw(
					_("{0} {1} cannot be a leaf node as it has children").format(_(self.pagetype), self.name)
				)

	def get_ancestors(self):
		return get_ancestors_of(self.pagetype, self.name)

	def get_parent(self) -> "NestedSet":
		"""Return the parent Page."""
		parent_name = self.get(self.nsm_parent_field)
		if parent_name:
			return jingrow.get_pg(self.pagetype, parent_name)

	def get_children(self) -> Iterator["NestedSet"]:
		"""Return a generator that yields child Documents."""
		child_names = jingrow.get_list(self.pagetype, filters={self.nsm_parent_field: self.name}, pluck="name")
		for name in child_names:
			yield jingrow.get_pg(self.pagetype, name)


def get_root_of(pagetype):
	"""Get root element of a PageType with a tree structure"""
	from jingrow.query_builder.functions import Count

	Table = PageType(pagetype)
	t1 = Table.as_("t1")
	t2 = Table.as_("t2")

	node_query = SubQuery(jingrow.qb.from_(t2).select(Count("*")).where((t2.lft < t1.lft) & (t2.rgt > t1.rgt)))
	result = jingrow.qb.from_(t1).select(t1.name).where((node_query == 0) & (t1.rgt > t1.lft)).run()

	return result[0][0] if result else None


def get_ancestors_of(pagetype, name, order_by="lft desc", limit=None):
	"""Get ancestor elements of a PageType with a tree structure"""
	lft, rgt = jingrow.db.get_value(pagetype, name, ["lft", "rgt"])

	return jingrow.get_all(
		pagetype,
		{"lft": ["<", lft], "rgt": [">", rgt]},
		"name",
		order_by=order_by,
		limit_page_length=limit,
		pluck="name",
	)


def get_descendants_of(pagetype, name, order_by="lft desc", limit=None, ignore_permissions=False):
	"""Return descendants of the current record"""
	lft, rgt = jingrow.db.get_value(pagetype, name, ["lft", "rgt"])

	if rgt - lft <= 1:
		return []

	return jingrow.get_list(
		pagetype,
		{"lft": [">", lft], "rgt": ["<", rgt]},
		"name",
		order_by=order_by,
		limit_page_length=limit,
		ignore_permissions=ignore_permissions,
		pluck="name",
	)
