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

from typing import TYPE_CHECKING

import jingrow
from jingrow import _
from jingrow.desk.pagetype.notification_log.notification_log import (
	enqueue_create_notification,
	get_title,
	get_title_html,
)
from jingrow.desk.form.page_follow import follow_document
from jingrow.utils import cint

if TYPE_CHECKING:
	from jingrow.model.page import Page


@jingrow.whitelist()
def add(pagetype, name, user=None, read=1, write=0, submit=0, share=0, everyone=0, notify=0):
	"""Expose function without flags to the client-side"""
	return add_pageshare(
		pagetype,
		name,
		user=user,
		read=read,
		write=write,
		submit=submit,
		share=share,
		everyone=everyone,
		notify=notify,
	)


def add_pageshare(
	pagetype, name, user=None, read=1, write=0, submit=0, share=0, everyone=0, flags=None, notify=0
):
	"""Share the given document with a user."""
	if not user:
		user = jingrow.session.user

	if not (flags or {}).get("ignore_share_permission"):
		check_share_permission(pagetype, name)

	share_name = get_share_name(pagetype, name, user, everyone)

	if share_name:
		pg = jingrow.get_pg("PageShare", share_name)
	else:
		pg = jingrow.new_pg("PageShare")
		pg.update({"user": user, "share_pagetype": pagetype, "share_name": name, "everyone": cint(everyone)})

	if flags:
		pg.flags.update(flags)

	pg.update(
		{
			# always add read, since you are adding!
			"read": 1,
			"write": cint(write),
			"submit": cint(submit),
			"share": cint(share),
		}
	)

	pg.save(ignore_permissions=True)
	notify_assignment(user, pagetype, name, everyone, notify=notify)

	if jingrow.get_cached_value("User", user, "follow_shared_documents"):
		follow_document(pagetype, name, user)

	return pg


def remove(pagetype, name, user, flags=None):
	share_name = jingrow.db.get_value("PageShare", {"user": user, "share_name": name, "share_pagetype": pagetype})

	if share_name:
		jingrow.delete_pg("PageShare", share_name, flags=flags)


@jingrow.whitelist()
def set_permission(pagetype, name, user, permission_to, value=1, everyone=0):
	"""Expose function without flags to the client-side"""
	return set_pageshare_permission(pagetype, name, user, permission_to, value=value, everyone=everyone)


def set_pageshare_permission(pagetype, name, user, permission_to, value=1, everyone=0, flags=None):
	"""Set share permission."""
	if not (flags or {}).get("ignore_share_permission"):
		check_share_permission(pagetype, name)

	share_name = get_share_name(pagetype, name, user, everyone)
	value = int(value)

	if not share_name:
		if value:
			share = add_pageshare(pagetype, name, user, everyone=everyone, **{permission_to: 1}, flags=flags)
		else:
			# no share found, nothing to remove
			share = None

	else:
		share = jingrow.get_pg("PageShare", share_name)
		if flags:
			share.flags.update(flags)
		share.flags.ignore_permissions = True
		share.set(permission_to, value)

		if not value:
			# un-set higher-order permissions too
			if permission_to == "read":
				share.read = share.write = share.submit = share.share = 0

		share.save()

		if not (share.read or share.write or share.submit or share.share):
			share.delete()
			share = None

	return share


@jingrow.whitelist()
def get_users(pagetype: str, name: str) -> list:
	"""Get list of users with which this document is shared"""
	pg = jingrow.get_pg(pagetype, name)
	return _get_users(pg)


def _get_users(pg: "Page") -> list:
	from jingrow.permissions import has_permission

	if not has_permission(pg.pagetype, "read", pg, raise_exception=False):
		return []

	return jingrow.get_all(
		"PageShare",
		fields=[
			"name",
			"user",
			"read",
			"write",
			"submit",
			"share",
			"everyone",
			"owner",
			"creation",
		],
		filters=dict(share_pagetype=pg.pagetype, share_name=pg.name),
	)


def get_shared(pagetype, user=None, rights=None, *, filters=None, limit=None):
	"""Get list of shared document names for given user and PageType.

	:param pagetype: PageType of which shared names are queried.
	:param user: User for which shared names are queried.
	:param rights: List of rights for which the document is shared. List of `read`, `write`, `share`"""

	if not user:
		user = jingrow.session.user

	if not rights:
		rights = ["read"]

	share_filters = [[right, "=", 1] for right in rights]
	share_filters += [["share_pagetype", "=", pagetype]]
	if filters:
		share_filters += filters

	or_filters = [["user", "=", user]]
	if user != "Guest":
		or_filters += [["everyone", "=", 1]]

	shared_pgs = jingrow.get_all(
		"PageShare",
		fields=["share_name"],
		filters=share_filters,
		or_filters=or_filters,
		order_by=None,
		limit_page_length=limit,
	)

	return [pg.share_name for pg in shared_pgs]


def get_shared_pagetypes(user=None):
	"""Return list of pagetypes in which documents are shared for the given user."""
	if not user:
		user = jingrow.session.user
	table = jingrow.qb.PageType("PageShare")
	query = (
		jingrow.qb.from_(table)
		.where((table.user == user) | (table.everyone == 1))
		.select(table.share_pagetype)
		.distinct()
	)
	return query.run(pluck=True)


def get_share_name(pagetype, name, user, everyone):
	if cint(everyone):
		share_name = jingrow.db.get_value(
			"PageShare", {"everyone": 1, "share_name": name, "share_pagetype": pagetype}
		)
	else:
		share_name = jingrow.db.get_value(
			"PageShare", {"user": user, "share_name": name, "share_pagetype": pagetype}
		)

	return share_name


def check_share_permission(pagetype, name):
	"""Check if the user can share with other users"""
	if not jingrow.has_permission(pagetype, ptype="share", pg=name):
		jingrow.throw(
			_("No permission to {0} {1} {2}").format("share", _(pagetype), name), jingrow.PermissionError
		)


def notify_assignment(shared_by, pagetype, pg_name, everyone, notify=0):
	if not (shared_by and pagetype and pg_name) or everyone or not notify:
		return

	from jingrow.utils import get_fullname

	title = get_title(pagetype, pg_name)

	reference_user = get_fullname(jingrow.session.user)
	notification_message = _("{0} shared a document {1} {2} with you").format(
		jingrow.bold(reference_user), jingrow.bold(_(pagetype)), get_title_html(title)
	)

	notification_pg = {
		"type": "Share",
		"document_type": pagetype,
		"subject": notification_message,
		"document_name": pg_name,
		"from_user": jingrow.session.user,
	}

	enqueue_create_notification(shared_by, notification_pg)
