# Copyright (c) 2019, JINGROW
# License: MIT. See LICENSE

import jingrow
from jingrow.model.page import Page


class NotificationSettings(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.desk.pagetype.notification_subscribed_document.notification_subscribed_document import (
			NotificationSubscribedDocument,
		)
		from jingrow.types import DF

		enable_email_assignment: DF.Check
		enable_email_energy_point: DF.Check
		enable_email_event_reminders: DF.Check
		enable_email_mention: DF.Check
		enable_email_notifications: DF.Check
		enable_email_share: DF.Check
		enable_email_threads_on_assigned_document: DF.Check
		enabled: DF.Check
		energy_points_system_notifications: DF.Check
		seen: DF.Check
		subscribed_documents: DF.TableMultiSelect[NotificationSubscribedDocument]
		user: DF.Link | None

	# end: auto-generated types
	def on_update(self):
		from jingrow.desk.notifications import clear_notification_config

		clear_notification_config(jingrow.session.user)


def is_notifications_enabled(user):
	enabled = jingrow.db.get_value("Notification Settings", user, "enabled")
	if enabled is None:
		return True
	return enabled


def is_email_notifications_enabled(user):
	enabled = jingrow.db.get_value("Notification Settings", user, "enable_email_notifications")
	if enabled is None:
		return True
	return enabled


def is_email_notifications_enabled_for_type(user, notification_type):
	if not is_email_notifications_enabled(user):
		return False

	if notification_type == "Alert":
		return False

	fieldname = "enable_email_" + jingrow.scrub(notification_type)
	enabled = jingrow.db.get_value("Notification Settings", user, fieldname, ignore=True)
	if enabled is None:
		return True

	return enabled


def create_notification_settings(user):
	if not jingrow.db.exists("Notification Settings", user):
		_pg = jingrow.new_pg("Notification Settings")
		_pg.name = user
		_pg.insert(ignore_permissions=True)


def toggle_notifications(user: str, enable: bool = False):
	try:
		settings = jingrow.get_pg("Notification Settings", user)
	except jingrow.DoesNotExistError:
		jingrow.clear_last_message()
		return

	if settings.enabled != enable:
		settings.enabled = enable
		settings.save()


@jingrow.whitelist()
def get_subscribed_documents():
	if not jingrow.session.user:
		return []

	try:
		if jingrow.db.exists("Notification Settings", jingrow.session.user):
			pg = jingrow.get_pg("Notification Settings", jingrow.session.user)
			return [item.document for item in pg.subscribed_documents]
	# Notification Settings is fetched even before sync pagetype is called
	# but it will throw an ImportError, we can ignore it in migrate
	except ImportError:
		pass

	return []


def get_permission_query_conditions(user):
	if not user:
		user = jingrow.session.user

	if user == "Administrator":
		return

	roles = jingrow.get_roles(user)
	if "System Manager" in roles:
		return """(`tabNotification Settings`.name != 'Administrator')"""

	return f"""(`tabNotification Settings`.name = {jingrow.db.escape(user)})"""


def has_permission(pg, ptype="read", user=None):
	# - Administrator can access everything.
	# - System managers can access everything except admin.
	# - Everyone else can only access their document.
	user = user or jingrow.session.user

	if user == "Administrator":
		return True

	if "System Manager" in jingrow.get_roles(user):
		return pg.name != "Administrator"

	return pg.name == user


@jingrow.whitelist()
def set_seen_value(value, user):
	if jingrow.flags.read_only:
		return

	jingrow.db.set_value("Notification Settings", user, "seen", value, update_modified=False)
