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

from contextlib import suppress

import jingrow
from jingrow import _
from jingrow.rate_limiter import rate_limit
from jingrow.utils import escape_html, validate_email_address

sitemap = 1


def get_context(context):
	pg = jingrow.get_pg("Contact Us Settings", "Contact Us Settings")

	if pg.query_options:
		query_options = [opt.strip() for opt in pg.query_options.replace(",", "\n").split("\n") if opt]
	else:
		query_options = ["Sales", "Support", "General"]

	out = {"query_options": query_options, "parents": [{"name": _("Home"), "route": "/"}]}
	out.update(pg.as_dict())

	return out


@jingrow.whitelist(allow_guest=True)
@rate_limit(limit=1000, seconds=60 * 60)
def send_message(sender, message, subject="Website Query"):
	sender = validate_email_address(sender, throw=True)

	message = escape_html(message)

	with suppress(jingrow.OutgoingEmailError):
		if forward_to_email := jingrow.db.get_single_value("Contact Us Settings", "forward_to_email"):
			jingrow.sendmail(recipients=forward_to_email, reply_to=sender, content=message, subject=subject)

		reply = _(
			"""Thank you for reaching out to us. We will get back to you at the earliest.


Your query:

{0}"""
		).format(message)
		jingrow.sendmail(
			recipients=sender,
			content=f"<div style='white-space: pre-wrap'>{reply}</div>",
			subject=_("We've received your query!"),
		)

	# for clearing outgoing email error message
	jingrow.clear_last_message()

	system_language = jingrow.db.get_single_value("System Settings", "language")
	# add to Email
	jingrow.get_pg(
		dict(
			pagetype="Email",
			sender=sender,
			subject=_("New Message from Website Contact Page", system_language),
			sent_or_received="Received",
			content=message,
			status="Open",
		)
	).insert(ignore_permissions=True)
