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

import jingrow
from jingrow import _
from jingrow.model.page import Page
from jingrow.utils import cint
from jingrow.utils.data import add_to_date, get_datetime, now_datetime


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

		description: DF.SmallText
		notified: DF.Check
		remind_at: DF.Datetime
		reminder_pagename: DF.DynamicLink | None
		reminder_pagetype: DF.Link | None
		user: DF.Link

	# end: auto-generated types
	@staticmethod
	def clear_old_logs(days=30):
		from jingrow.query_builder import Interval
		from jingrow.query_builder.functions import Now

		table = jingrow.qb.PageType("Reminder")
		jingrow.db.delete(table, filters=(table.remind_at < (Now() - Interval(days=days))))

	def validate(self):
		self.user = jingrow.session.user
		if get_datetime(self.remind_at) < now_datetime():
			jingrow.throw(_("Reminder cannot be created in past."))

	def send_reminder(self):
		if self.notified:
			return

		self.db_set("notified", 1, update_modified=False)

		try:
			notification = jingrow.new_pg("Notification Log")
			notification.for_user = self.user
			notification.set("type", "Alert")
			notification.document_type = self.reminder_pagetype
			notification.document_name = self.reminder_pagename
			notification.subject = self.description
			notification.insert()
		except Exception:
			self.log_error("Failed to send reminder")


@jingrow.whitelist()
def create_new_reminder(
	remind_at: str,
	description: str,
	reminder_pagetype: str | None = None,
	reminder_pagename: str | None = None,
):
	reminder = jingrow.new_pg("Reminder")

	reminder.description = description
	reminder.remind_at = remind_at
	reminder.reminder_pagetype = reminder_pagetype
	reminder.reminder_pagename = reminder_pagename

	return reminder.insert()


def send_reminders():
	# Ensure that we send all reminders that might be before next job execution.
	job_freq = 15 * 60  # 15 minutes, as specified in hooks.py
	upper_threshold = add_to_date(now_datetime(), seconds=job_freq, as_string=True, as_datetime=True)
	lower_threshold = add_to_date(now_datetime(), hours=-1, as_string=True, as_datetime=True)

	pending_reminders = jingrow.get_all(
		"Reminder",
		filters=[
			("remind_at", "<=", upper_threshold),
			("remind_at", ">=", lower_threshold),  # dont send too old reminders if failed to send
			("notified", "=", 0),
		],
		pluck="name",
		ignore_ifnull=True,
	)

	for reminder in pending_reminders:
		jingrow.get_pg("Reminder", reminder).send_reminder()
