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

"""Allow adding of likes to documents"""

import json

import jingrow
from jingrow import _
from jingrow.database.schema import add_column
from jingrow.desk.form.page_follow import follow_document
from jingrow.utils import get_link_to_form


@jingrow.whitelist()
def toggle_like(pagetype, name, add=False):
	"""Adds / removes the current user in the `__liked_by` property of the given document.
	If column does not exist, will add it in the database.

	The `_liked_by` property is always set from this function and is ignored if set via
	Page API

	:param pagetype: PageType of the document to like
	:param name: Name of the document to like
	:param add: `Yes` if like is to be added. If not `Yes` the like will be removed."""

	_toggle_like(pagetype, name, add)


def _toggle_like(pagetype, name, add, user=None):
	"""Same as toggle_like but hides param `user` from API"""

	if not user:
		user = jingrow.session.user

	try:
		liked_by = jingrow.db.get_value(pagetype, name, "_liked_by")

		if liked_by:
			liked_by = json.loads(liked_by)
		else:
			liked_by = []

		if add == "Yes":
			if user not in liked_by:
				liked_by.append(user)
				add_comment(pagetype, name)
				if jingrow.get_cached_value("User", user, "follow_liked_documents"):
					follow_document(pagetype, name, user)
		else:
			if user in liked_by:
				liked_by.remove(user)
				remove_like(pagetype, name)

		if jingrow.get_meta(pagetype).issingle:
			jingrow.db.set_single_value(pagetype, "_liked_by", json.dumps(liked_by), update_modified=False)
		else:
			jingrow.db.set_value(pagetype, name, "_liked_by", json.dumps(liked_by), update_modified=False)

	except jingrow.db.ProgrammingError as e:
		if jingrow.db.is_missing_column(e):
			add_column(pagetype, "_liked_by", "Text")
			_toggle_like(pagetype, name, add, user)
		else:
			raise


def remove_like(pagetype, name):
	"""Remove previous Like"""
	# remove Comment
	jingrow.delete_pg(
		"Comment",
		[
			c.name
			for c in jingrow.get_all(
				"Comment",
				filters={
					"comment_type": "Like",
					"reference_pagetype": pagetype,
					"reference_name": name,
					"owner": jingrow.session.user,
				},
			)
		],
		ignore_permissions=True,
	)


def add_comment(pagetype, name):
	pg = jingrow.get_pg(pagetype, name)
	pg.add_comment("Like", _("Liked"))
