# Copyright (c) 2015, InfluxFramework LLC
# License: MIT. See LICENSE

import influxframework
from influxframework import _
from influxframework.model.document import Document


class EmailUnsubscribe(Document):
	def validate(self):
		if not self.global_unsubscribe and not (self.reference_doctype and self.reference_name):
			influxframework.throw(_("Reference DocType and Reference Name are required"), influxframework.MandatoryError)

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

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

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

	def on_update(self):
		if self.reference_doctype and self.reference_name:
			doc = influxframework.get_doc(self.reference_doctype, self.reference_name)
			doc.add_comment("Label", _("Left this conversation"), comment_email=self.email)
