import jingrow

from jcloud.jcloud.pagetype.jcloud_role.jcloud_role import check_role_permissions
from jcloud.utils import get_current_team


@jingrow.whitelist()
def get_notifications(filters=None, order_by="creation desc", limit_start=None, limit_page_length=None):
	if not filters:
		filters = {}

	JcloudNotification = jingrow.qb.PageType("Jcloud Notification")
	query = (
		jingrow.qb.from_(JcloudNotification)
		.select(
			JcloudNotification.name,
			JcloudNotification.type,
			JcloudNotification.read,
			JcloudNotification.title,
			JcloudNotification.message,
			JcloudNotification.creation,
			JcloudNotification.is_addressed,
			JcloudNotification.is_actionable,
			JcloudNotification.document_type,
			JcloudNotification.document_name,
		)
		.where(JcloudNotification.team == get_current_team())
		.orderby(JcloudNotification.creation, order=jingrow.qb.desc)
		.limit(limit_page_length)
		.offset(limit_start)
	)

	if roles := set(check_role_permissions("Site") + check_role_permissions("Release Group")):
		JcloudRolePermission = jingrow.qb.PageType("Jcloud Role Permission")

		query = (
			query.join(JcloudRolePermission)
			.on(
				(
					(JcloudRolePermission.site == JcloudNotification.reference_name)
					| (JcloudRolePermission.release_group == JcloudNotification.reference_name)
				)
				& JcloudRolePermission.role.isin(roles)
			)
			.distinct()
		)

	if filters.get("read") == "Unread":
		query = query.where(JcloudNotification.read == 0)

	notifications = query.run(as_dict=True)

	for notification in notifications:
		if notification.document_type == "Deploy Candidate":
			rg_name = jingrow.db.get_value("Deploy Candidate", notification.document_name, "group")
			notification.route = f"groups/{rg_name}/deploys/{notification.document_name}"
		elif notification.document_type == "Agent Job":
			site_name = jingrow.db.get_value("Agent Job", notification.document_name, "site")
			notification.route = (
				f"sites/{site_name}/insights/jobs/{notification.document_name}" if site_name else None
			)
		else:
			notification.route = None

	return notifications


@jingrow.whitelist()
def mark_all_notifications_as_read():
	jingrow.db.set_value("Jcloud Notification", {"team": get_current_team()}, "read", 1, update_modified=False)


@jingrow.whitelist()
def get_unread_count():
	return jingrow.db.count("Jcloud Notification", {"read": False, "team": get_current_team()})
