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

import jingrow
from jingrow import _
from jingrow.rate_limiter import rate_limit
from jingrow.website.pagetype.blog_settings.blog_settings import get_like_limit
from jingrow.website.utils import clear_cache


@jingrow.whitelist(allow_guest=True)
@rate_limit(key="reference_name", limit=get_like_limit, seconds=60 * 60)
def like(reference_pagetype, reference_name, like, route=""):
	like = jingrow.parse_json(like)
	ref_pg = jingrow.get_pg(reference_pagetype, reference_name)
	if ref_pg.disable_likes == 1:
		return

	if like:
		liked = add_like(reference_pagetype, reference_name)
	else:
		liked = delete_like(reference_pagetype, reference_name)

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

	if like and ref_pg.enable_email_notification:
		ref_pg_title = ref_pg.get_title()
		subject = _("Like on {0}: {1}").format(reference_pagetype, ref_pg_title)
		content = _("You have received a ❤️ like on your blog post")
		message = f"<p>{content} <b>{ref_pg_title}</b></p>"
		message = message + "<p><a href='{}/{}#likes' style='font-size: 80%'>{}</a></p>".format(
			jingrow.utils.get_request_site_address(), ref_pg.route, _("View Blog Post")
		)

		# notify creator
		jingrow.sendmail(
			recipients=jingrow.db.get_value("User", ref_pg.owner, "email") or ref_pg.owner,
			subject=subject,
			message=message,
			reference_pagetype=ref_pg.pagetype,
			reference_name=ref_pg.name,
		)

	return liked


def add_like(reference_pagetype, reference_name):
	user = jingrow.session.user

	like = jingrow.new_pg("Comment")
	like.comment_type = "Like"
	like.comment_email = user
	like.reference_pagetype = reference_pagetype
	like.reference_name = reference_name
	like.content = "Liked by: " + user
	if user == "Guest":
		like.ip_address = jingrow.local.request_ip
	like.save(ignore_permissions=True)
	return True


def delete_like(reference_pagetype, reference_name):
	user = jingrow.session.user

	filters = {
		"comment_type": "Like",
		"comment_email": user,
		"reference_pagetype": reference_pagetype,
		"reference_name": reference_name,
	}

	if user == "Guest":
		filters["ip_address"] = jingrow.local.request_ip

	jingrow.db.delete("Comment", filters)
	return False
