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

import jingrow
from jingrow.model import is_default_field
from jingrow.query_builder import Order
from jingrow.query_builder.functions import Count
from jingrow.query_builder.terms import SubQuery
from jingrow.query_builder.utils import PageType


@jingrow.whitelist()
def get_list_settings(pagetype):
	try:
		return jingrow.get_cached_pg("List View Settings", pagetype)
	except jingrow.DoesNotExistError:
		jingrow.clear_messages()


@jingrow.whitelist()
def set_list_settings(pagetype, values):
	try:
		pg = jingrow.get_pg("List View Settings", pagetype)
	except jingrow.DoesNotExistError:
		pg = jingrow.new_pg("List View Settings")
		pg.name = pagetype
		jingrow.clear_messages()
	pg.update(jingrow.parse_json(values))
	pg.save()


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

	if field == "assigned_to":
		ToDo = PageType("ToDo")
		User = PageType("User")
		count = Count("*").as_("count")
		filtered_records = jingrow.qb.get_query(
			pagetype,
			filters=current_filters,
			fields=["name"],
			validate_filters=True,
		)

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

	if not jingrow.get_meta(pagetype).has_field(field) and not is_default_field(field):
		raise ValueError("Field does not belong to pagetype")

	data = jingrow.get_list(
		pagetype,
		filters=current_filters,
		group_by=f"`tab{pagetype}`.{field}",
		fields=["count(*) as count", f"`{field}` as name"],
		order_by="count desc",
	)

	if field == "owner":
		owner_idx = None

		for idx, item in enumerate(data):
			if item.name == jingrow.session.user:
				owner_idx = idx
				break

		if owner_idx:
			data = [data.pop(owner_idx)] + data[0:49]
		else:
			data = data[0:50]
	else:
		data = data[0:50]

	return data
