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

import jingrow
from jingrow import _
from jingrow.model.page import Page


class EmailUnsubscribe(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

		email: DF.Data
		global_unsubscribe: DF.Check
		reference_pagetype: DF.Link | None
		reference_name: DF.DynamicLink | None

	# end: auto-generated types
	def validate(self):
		if not self.global_unsubscribe and not (self.reference_pagetype and self.reference_name):
			jingrow.throw(_("Reference PageType and Reference Name are required"), jingrow.MandatoryError)

		if not self.global_unsubscribe and jingrow.db.get_value(self.pagetype, self.name, "global_unsubscribe"):
			jingrow.throw(_("Delete this record to allow sending to this email address"))

		if self.global_unsubscribe:
			if jingrow.get_all(
				"Email Unsubscribe",
				filters={"email": self.email, "global_unsubscribe": 1, "name": ["!=", self.name]},
			):
				jingrow.throw(_("{0} already unsubscribed").format(self.email), jingrow.DuplicateEntryError)

		else:
			if jingrow.get_all(
				"Email Unsubscribe",
				filters={
					"email": self.email,
					"reference_pagetype": self.reference_pagetype,
					"reference_name": self.reference_name,
					"name": ["!=", self.name],
				},
			):
				jingrow.throw(
					_("{0} already unsubscribed for {1} {2}").format(
						self.email, self.reference_pagetype, self.reference_name
					),
					jingrow.DuplicateEntryError,
				)

	def on_update(self):
		if self.reference_pagetype and self.reference_name:
			pg = jingrow.get_pg(self.reference_pagetype, self.reference_name)
			pg.add_comment("Label", _("Left this conversation"), comment_email=self.email)
