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

import jingrow
from jingrow import _
from jingrow.model.page import Page
from jingrow.utils import cint, get_fullname

exclude_from_linked_with = True


class PageShare(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.types import DF

		everyone: DF.Check
		notify_by_email: DF.Check
		read: DF.Check
		share: DF.Check
		share_pagetype: DF.Link
		share_name: DF.DynamicLink
		submit: DF.Check
		user: DF.Link | None
		write: DF.Check
	# end: auto-generated types
	no_feed_on_delete = True

	def validate(self):
		self.validate_user()
		self.check_share_permission()
		self.check_is_submittable()
		self.cascade_permissions_downwards()
		self.get_pg().run_method("validate_share", self)

	def cascade_permissions_downwards(self):
		if self.share or self.write or self.submit:
			self.read = 1
		if self.submit:
			self.write = 1

	def get_pg(self):
		if not getattr(self, "_pg", None):
			self._pg = jingrow.get_pg(self.share_pagetype, self.share_name)
		return self._pg

	def validate_user(self):
		if self.everyone:
			self.user = None
		elif not self.user:
			jingrow.throw(_("User is mandatory for Share"), jingrow.MandatoryError)

	def check_share_permission(self):
		if not self.flags.ignore_share_permission and not jingrow.has_permission(
			self.share_pagetype, "share", self.get_pg()
		):
			jingrow.throw(_('You need to have "Share" permission'), jingrow.PermissionError)

	def check_is_submittable(self):
		if self.submit and not cint(jingrow.db.get_value("PageType", self.share_pagetype, "is_submittable")):
			jingrow.throw(
				_("Cannot share {0} with submit permission as the pagetype {1} is not submittable").format(
					jingrow.bold(self.share_name), jingrow.bold(self.share_pagetype)
				)
			)

	def after_insert(self):
		pg = self.get_pg()
		owner = get_fullname(self.owner)

		if self.everyone:
			pg.add_comment("Shared", _("{0} shared this document with everyone").format(owner))
		else:
			pg.add_comment(
				"Shared", _("{0} shared this document with {1}").format(owner, get_fullname(self.user))
			)

	def on_trash(self):
		if not self.flags.ignore_share_permission:
			self.check_share_permission()

		self.get_pg().add_comment(
			"Unshared",
			_("{0} un-shared this document with {1}").format(
				get_fullname(self.owner), get_fullname(self.user)
			),
		)


def on_pagetype_update():
	"""Add index in `tabPageShare` for `(user, share_pagetype)`"""
	jingrow.db.add_index("PageShare", ["user", "share_pagetype"])
	jingrow.db.add_index("PageShare", ["share_pagetype", "share_name"])
