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

import json
from typing import TYPE_CHECKING

import jingrow
import jingrow.desk.form.load
import jingrow.desk.form.meta
from jingrow import _
from jingrow.core.pagetype.file.utils import extract_images_from_html
from jingrow.desk.form.page_follow import follow_document

if TYPE_CHECKING:
	from jingrow.core.pagetype.comment.comment import Comment


@jingrow.whitelist(methods=["DELETE", "POST"])
def remove_attach():
	"""remove attachment"""
	fid = jingrow.form_dict.get("fid")
	jingrow.delete_pg("File", fid)


@jingrow.whitelist(methods=["POST", "PUT"])
def add_comment(
	reference_pagetype: str, reference_name: str, content: str, comment_email: str, comment_by: str
) -> "Comment":
	"""Allow logged user with permission to read document to add a comment"""
	reference_pg = jingrow.get_pg(reference_pagetype, reference_name)
	reference_pg.check_permission()

	comment = jingrow.new_pg("Comment")
	comment.update(
		{
			"comment_type": "Comment",
			"reference_pagetype": reference_pagetype,
			"reference_name": reference_name,
			"comment_email": comment_email,
			"comment_by": comment_by,
			"content": extract_images_from_html(reference_pg, content, is_private=True),
		}
	)
	comment.insert(ignore_permissions=True)

	if jingrow.get_cached_value("User", jingrow.session.user, "follow_commented_documents"):
		follow_document(comment.reference_pagetype, comment.reference_name, jingrow.session.user)

	return comment


@jingrow.whitelist()
def update_comment(name, content):
	"""allow only owner to update comment"""
	pg = jingrow.get_pg("Comment", name)

	if jingrow.session.user not in ["Administrator", pg.owner]:
		jingrow.throw(_("Comment can only be edited by the owner"), jingrow.PermissionError)

	if pg.reference_pagetype and pg.reference_name:
		reference_pg = jingrow.get_pg(pg.reference_pagetype, pg.reference_name)
		reference_pg.check_permission()

		pg.content = extract_images_from_html(reference_pg, content, is_private=True)
	else:
		pg.content = content

	pg.save(ignore_permissions=True)


@jingrow.whitelist()
def get_next(pagetype, value, prev, filters=None, sort_order="desc", sort_field="modified"):
	prev = int(prev)
	if not filters:
		filters = []
	if isinstance(filters, str):
		filters = json.loads(filters)

	# # condition based on sort order
	condition = ">" if sort_order.lower() == "asc" else "<"

	# switch the condition
	if prev:
		sort_order = "asc" if sort_order.lower() == "desc" else "desc"
		condition = "<" if condition == ">" else ">"

	# # add condition for next or prev item
	filters.append([pagetype, sort_field, condition, jingrow.get_value(pagetype, value, sort_field)])

	res = jingrow.get_list(
		pagetype,
		fields=["name"],
		filters=filters,
		order_by=f"`tab{pagetype}`.{sort_field}" + " " + sort_order,
		limit_start=0,
		limit_page_length=1,
		as_list=True,
	)

	if not res:
		jingrow.msgprint(_("No further records"))
		return None
	else:
		return res[0][0]


def get_pdf_link(pagetype, pagename, print_format="Standard", no_letterhead=0):
	return f"/api/action/jingrow.utils.print_format.download_pdf?pagetype={pagetype}&name={pagename}&format={print_format}&no_letterhead={no_letterhead}"
