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

import jingrow
from jingrow import _, scrub
from jingrow.rate_limiter import rate_limit
from jingrow.utils.html_utils import clean_html
from jingrow.website.pagetype.blog_settings.blog_settings import get_comment_limit
from jingrow.website.utils import clear_cache

URLS_COMMENT_PATTERN = re.compile(
	r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", re.IGNORECASE
)
EMAIL_PATTERN = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", re.IGNORECASE)


@jingrow.whitelist(allow_guest=True)
@rate_limit(key="reference_name", limit=get_comment_limit, seconds=60 * 60)
def add_comment(comment, comment_email, comment_by, reference_pagetype, reference_name, route):
	if jingrow.session.user == "Guest":
		if reference_pagetype not in ("Blog Post", "Web Page"):
			return

		if reference_pagetype == "Blog Post" and not jingrow.db.get_single_value(
			"Blog Settings", "allow_guest_to_comment"
		):
			return

		if jingrow.db.exists("User", comment_email):
			jingrow.throw(_("Please login to post a comment."))

	if not comment.strip():
		jingrow.msgprint(_("The comment cannot be empty"))
		return False

	if URLS_COMMENT_PATTERN.search(comment) or EMAIL_PATTERN.search(comment):
		jingrow.msgprint(_("Comments cannot have links or email addresses"))
		return False

	pg = jingrow.get_pg(reference_pagetype, reference_name)
	comment = pg.add_comment(text=clean_html(comment), comment_email=comment_email, comment_by=comment_by)

	comment.db_set("published", 1)

	# since comments are embedded in the page, clear the web cache
	if route:
		clear_cache(route)

	if pg.get("route"):
		url = f"{jingrow.utils.get_request_site_address()}/{pg.route}#{comment.name}"
	else:
		url = f"{jingrow.utils.get_request_site_address()}/app/{scrub(pg.pagetype)}/{pg.name}#comment-{comment.name}"

	content = comment.content + "<p><a href='{}' style='font-size: 80%'>{}</a></p>".format(
		url, _("View Comment")
	)

	if pg.pagetype != "Blog Post" or pg.enable_email_notification:
		# notify creator
		creator_email = jingrow.db.get_value("User", pg.owner, "email") or pg.owner
		subject = _("New Comment on {0}: {1}").format(pg.pagetype, pg.get_title())

		jingrow.sendmail(
			recipients=creator_email,
			subject=subject,
			message=content,
			reference_pagetype=pg.pagetype,
			reference_name=pg.name,
		)

	# revert with template if all clear (no backlinks)
	template = jingrow.get_template("templates/includes/comments/comment.html")
	return template.render({"comment": comment.as_dict()})
