# Copyright (c) 2015, JINGROW and contributors
# License: MIT. See LICENSE

from contextlib import suppress

import redis

import jingrow
from jingrow.utils.data import cstr


def publish_progress(percent, title=None, pagetype=None, pagename=None, description=None, task_id=None):
	publish_realtime(
		"progress",
		{"percent": percent, "title": title, "description": description},
		user=None if pagetype and pagename else jingrow.session.user,
		pagetype=pagetype,
		pagename=pagename,
		task_id=task_id,
	)


def publish_realtime(
	event: str | None = None,
	message: dict | None = None,
	room: str | None = None,
	user: str | None = None,
	pagetype: str | None = None,
	pagename: str | None = None,
	task_id: str | None = None,
	after_commit: bool = False,
):
	"""Publish real-time updates

	:param event: Event name, like `task_progress` etc. that will be handled by the client (default is `task_progress` if within task or `global`)
	:param message: JSON message object. For async must contain `task_id`
	:param room: Room in which to publish update (default entire site)
	:param user: Transmit to user
	:param pagetype: Transmit to pagetype, pagename
	:param pagename: Transmit to pagetype, pagename
	:param after_commit: (default False) will emit after current transaction is committed"""
	if message is None:
		message = {}

	if not task_id and hasattr(jingrow.local, "task_id"):
		task_id = jingrow.local.task_id

	if event is None:
		event = "task_progress" if task_id else "global"
	elif event == "msgprint" and not user:
		user = jingrow.session.user
	elif event == "list_update":
		pagetype = pagetype or message.get("pagetype")
		room = get_pagetype_room(pagetype)
	elif event == "pageinfo_update":
		room = get_pg_room(pagetype, pagename)

	if not room:
		if task_id:
			after_commit = False
			if "task_id" not in message:
				message["task_id"] = task_id
			room = get_task_progress_room(task_id)
		elif user:
			# transmit to specific user: System, Website or Guest
			room = get_user_room(user)
		elif pagetype and pagename:
			room = get_pg_room(pagetype, pagename)
		else:
			# This will be broadcasted to all Desk users
			room = get_site_room()

	if after_commit:
		if not hasattr(jingrow.local, "_realtime_log"):
			jingrow.local._realtime_log = []
			jingrow.db.after_commit.add(flush_realtime_log)
			jingrow.db.after_rollback.add(clear_realtime_log)

		params = [event, message, room]
		if params not in jingrow.local._realtime_log:
			jingrow.local._realtime_log.append(params)
	else:
		emit_via_redis(event, message, room)


def flush_realtime_log():
	for args in jingrow.local._realtime_log:
		jingrow.realtime.emit_via_redis(*args)

	clear_realtime_log()


def clear_realtime_log():
	if hasattr(jingrow.local, "_realtime_log"):
		del jingrow.local._realtime_log


def emit_via_redis(event, message, room):
	"""Publish real-time updates via redis

	:param event: Event name, like `task_progress` etc.
	:param message: JSON message object. For async must contain `task_id`
	:param room: name of the room"""
	from jingrow.utils.background_jobs import get_redis_connection_without_auth

	with suppress(redis.exceptions.ConnectionError):
		r = get_redis_connection_without_auth()
		r.publish(
			"events",
			jingrow.as_json(
				{"event": event, "message": message, "room": room, "namespace": jingrow.local.site}
			),
		)


@jingrow.whitelist(allow_guest=True)
def can_subscribe_pg(pagetype: str, pagename: str) -> bool:
	jingrow.has_permission(pagetype, pg=pagename, throw=True)
	return True


@jingrow.whitelist(allow_guest=True)
def can_subscribe_pagetype(pagetype: str) -> bool:
	from jingrow.exceptions import PermissionError

	if not jingrow.has_permission(pagetype=pagetype, ptype="read"):
		raise PermissionError()

	return True


@jingrow.whitelist(allow_guest=True)
def get_user_info():
	user_type = jingrow.session.data.user_type
	# For requests with Bearer tokens, user_type is not set in the session data
	if not user_type:
		user_type = jingrow.get_cached_value("User", jingrow.session.user, "user_type")
	return {
		"user": jingrow.session.user,
		"user_type": user_type,
	}


def get_pagetype_room(pagetype):
	return f"pagetype:{pagetype}"


def get_pg_room(pagetype, pagename):
	return f"pg:{pagetype}/{cstr(pagename)}"


def get_user_room(user):
	return f"user:{user}"


def get_site_room():
	return "all"


def get_task_progress_room(task_id):
	return f"task_progress:{task_id}"


def get_website_room():
	return "website"
