# Copyright (c) 2021, JINGROW
# For license information, please see license.txt

import jingrow
from jingrow.model.page import Page
from jingrow.realtime import get_website_room


class DiscussionReply(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.types import DF

		reply: DF.TextEditor | None
		topic: DF.Link | None

	# end: auto-generated types
	def on_update(self):
		jingrow.publish_realtime(
			event="update_message",
			room=get_website_room(),
			message={"reply": jingrow.utils.md_to_html(self.reply), "reply_name": self.name},
			after_commit=True,
		)

	def after_insert(self):
		replies = jingrow.db.count("Discussion Reply", {"topic": self.topic})
		topic_info = jingrow.get_all(
			"Discussion Topic",
			{"name": self.topic},
			["reference_pagetype", "reference_pagename", "name", "title", "owner", "creation"],
		)

		template = jingrow.render_template(
			"jingrow/templates/discussions/reply_card.html",
			{
				"reply": self,
				"topic": {"name": self.topic},
				"loop": {"index": replies},
				"single_thread": True if not topic_info[0].title else False,
			},
		)

		sidebar = jingrow.render_template(
			"jingrow/templates/discussions/sidebar.html", {"topic": topic_info[0]}
		)

		new_topic_template = jingrow.render_template(
			"jingrow/templates/discussions/reply_section.html", {"topic": topic_info[0]}
		)

		jingrow.publish_realtime(
			event="publish_message",
			room=get_website_room(),
			message={
				"template": template,
				"topic_info": topic_info[0],
				"sidebar": sidebar,
				"new_topic_template": new_topic_template,
				"reply_owner": self.owner,
			},
			after_commit=True,
		)

	def after_delete(self):
		jingrow.publish_realtime(
			event="delete_message",
			room=get_website_room(),
			message={"reply_name": self.name},
			after_commit=True,
		)


@jingrow.whitelist()
def delete_message(reply_name):
	owner = jingrow.db.get_value("Discussion Reply", reply_name, "owner")
	if owner == jingrow.session.user:
		jingrow.delete_pg("Discussion Reply", reply_name)
