# Copyright (c) 2021, FOSS United and contributors
# For license information, please see license.txt

import jingrow
from jingrow.model.page import Page


class DiscussionTopic(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

		reference_pagename: DF.DynamicLink | None
		reference_pagetype: DF.Link | None
		title: DF.Data | None
	# end: auto-generated types
	pass


@jingrow.whitelist()
def submit_discussion(pagetype, pagename, reply, title, topic_name=None, reply_name=None):
	if reply_name:
		pg = jingrow.get_pg("Discussion Reply", reply_name)
		pg.reply = reply
		pg.save(ignore_permissions=True)
		return

	if topic_name:
		save_message(reply, topic_name)
		return topic_name

	topic = jingrow.get_pg(
		{
			"pagetype": "Discussion Topic",
			"title": title,
			"reference_pagetype": pagetype,
			"reference_pagename": pagename,
		}
	)
	topic.save(ignore_permissions=True)
	save_message(reply, topic.name)
	return topic.name


def save_message(reply, topic):
	jingrow.get_pg({"pagetype": "Discussion Reply", "reply": reply, "topic": topic}).save(
		ignore_permissions=True
	)
