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

import jingrow
from jingrow import _


@jingrow.whitelist()
def get_all_nodes(pagetype, label, parent, tree_method, **filters):
	"""Recursively gets all data from tree nodes"""

	if "cmd" in filters:
		del filters["cmd"]
	filters.pop("data", None)

	tree_method = jingrow.get_attr(tree_method)

	if tree_method not in jingrow.whitelisted:
		jingrow.throw(_("Not Permitted"), jingrow.PermissionError)

	data = tree_method(pagetype, parent, **filters)
	out = [dict(parent=label, data=data)]

	if "is_root" in filters:
		del filters["is_root"]
	to_check = [d.get("value") for d in data if d.get("expandable")]

	while to_check:
		parent = to_check.pop()
		data = tree_method(pagetype, parent, is_root=False, **filters)
		out.append(dict(parent=parent, data=data))
		for d in data:
			if d.get("expandable"):
				to_check.append(d.get("value"))

	return out


@jingrow.whitelist()
def get_children(pagetype, parent="", **filters):
	return _get_children(pagetype, parent)


def _get_children(pagetype, parent="", ignore_permissions=False):
	parent_field = "parent_" + jingrow.scrub(pagetype)
	filters = [[f"ifnull(`{parent_field}`,'')", "=", parent], ["pagestatus", "<", 2]]

	meta = jingrow.get_meta(pagetype)

	return jingrow.get_list(
		pagetype,
		fields=[
			"name as value",
			"{} as title".format(meta.get("title_field") or "name"),
			"is_group as expandable",
		],
		filters=filters,
		order_by="name",
		ignore_permissions=ignore_permissions,
	)


@jingrow.whitelist()
def add_node():
	args = make_tree_args(**jingrow.form_dict)
	pg = jingrow.get_pg(args)

	pg.save()


def make_tree_args(**kwarg):
	kwarg.pop("cmd", None)

	pagetype = kwarg["pagetype"]
	parent_field = "parent_" + jingrow.scrub(pagetype)

	if kwarg["is_root"] == "false":
		kwarg["is_root"] = False
	if kwarg["is_root"] == "true":
		kwarg["is_root"] = True

	kwarg.update({parent_field: kwarg.get("parent") or kwarg.get(parent_field)})

	return jingrow._dict(kwarg)
