# Copyright (c) 2015, SolutionERP LLC and Contributors
# License: GNU General Public License v3. See license.txt


import xhiveframework
from xhiveframework.utils.nestedset import NestedSet, get_root_of

from xhiveerp.utilities.transaction_base import delete_events


class Department(NestedSet):
	nsm_parent_field = "parent_department"

	def autoname(self):
		root = get_root_of("Department")
		if root and self.department_name != root:
			self.name = get_abbreviated_name(self.department_name, self.company)
		else:
			self.name = self.department_name

	def validate(self):
		if not self.parent_department:
			root = get_root_of("Department")
			if root:
				self.parent_department = root

	def before_rename(self, old, new, merge=False):
		# renaming consistency with abbreviation
		if not xhiveframework.get_cached_value("Company", self.company, "abbr") in new:
			new = get_abbreviated_name(new, self.company)

		return new

	def on_update(self):
		if not (xhiveframework.local.flags.ignore_update_nsm or xhiveframework.flags.in_setup_wizard):
			super(Department, self).on_update()

	def on_trash(self):
		super(Department, self).on_trash()
		delete_events(self.doctype, self.name)


def on_doctype_update():
	xhiveframework.db.add_index("Department", ["lft", "rgt"])


def get_abbreviated_name(name, company):
	abbr = xhiveframework.get_cached_value("Company", company, "abbr")
	new_name = "{0} - {1}".format(name, abbr)
	return new_name


@xhiveframework.whitelist()
def get_children(doctype, parent=None, company=None, is_root=False):
	fields = ["name as value", "is_group as expandable"]
	filters = {}

	if company == parent:
		filters["name"] = get_root_of("Department")
	elif company:
		filters["parent_department"] = parent
		filters["company"] = company
	else:
		filters["parent_department"] = parent

	return xhiveframework.get_all("Department", fields=fields, filters=filters, order_by="name")


@xhiveframework.whitelist()
def add_node():
	from xhiveframework.desk.treeview import make_tree_args

	args = xhiveframework.form_dict
	args = make_tree_args(**args)

	if args.parent_department == args.company:
		args.parent_department = None

	xhiveframework.get_doc(args).insert()
