# Copyright (c) 2022, InfluxFramework LLC
# License: MIT. See LICENSE

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


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


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


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

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

		return (
			influxframework.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 influxframework.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,
	)
