# Copyright (c) 2022, Xhive Global Ltd. and Contributors
# License: MIT. See LICENSE

import xhiveframework
from xhiveframework.query_builder import Order
from xhiveframework.query_builder.functions import Count
from xhiveframework.query_builder.terms import SubQuery
from xhiveframework.query_builder.utils import DocType


@xhiveframework.whitelist()
def get_list_settings(doctype):
	try:
		return xhiveframework.get_cached_doc("List View Settings", doctype)
	except xhiveframework.DoesNotExistError:
		xhiveframework.clear_messages()


@xhiveframework.whitelist()
def set_list_settings(doctype, values):
	try:
		doc = xhiveframework.get_doc("List View Settings", doctype)
	except xhiveframework.DoesNotExistError:
		doc = xhiveframework.new_doc("List View Settings")
		doc.name = doctype
		xhiveframework.clear_messages()
	doc.update(xhiveframework.parse_json(values))
	doc.save()


@xhiveframework.whitelist()
def get_group_by_count(doctype: str, current_filters: str, field: str) -> list[dict]:
	current_filters = xhiveframework.parse_json(current_filters)

	if field == "assigned_to":
		ToDo = DocType("ToDo")
		User = DocType("User")
		count = Count("*").as_("count")
		filtered_records = xhiveframework.qb.engine.build_conditions(doctype, current_filters).select("name")

		return (
			xhiveframework.qb.from_(ToDo)
			.from_(User)
			.select(ToDo.allocated_to.as_("name"), count)
			.where(
				(ToDo.status != "Cancelled")
				& (ToDo.allocated_to == User.name)
				& (User.user_type == "System User")
				& (ToDo.reference_name.isin(SubQuery(filtered_records)))
			)
			.groupby(ToDo.allocated_to)
			.orderby(count, order=Order.desc)
			.limit(50)
			.run(as_dict=True)
		)

	return xhiveframework.get_list(
		doctype,
		filters=current_filters,
		group_by=f"`tab{doctype}`.{field}",
		fields=["count(*) as count", f"`{field}` as name"],
		order_by="count desc",
		limit=50,
	)
