# Copyright (c) 2020, JINGROW
# For license information, please see license.txt
from __future__ import annotations

import jingrow
from jingrow.model.page import Page


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

		action: DF.Literal[
			"Activate Site",
			"Add Domain",
			"Archive",
			"Backup",
			"Create",
			"Clear Cache",
			"Deactivate Site",
			"Install App",
			"Login as Administrator",
			"Migrate",
			"Reinstall",
			"Restore",
			"Suspend Site",
			"Uninstall App",
			"Unsuspend Site",
			"Update",
			"Update Configuration",
			"Drop Offsite Backups",
			"Enable Database Access",
			"Disable Database Access",
			"Create Database User",
			"Remove Database User",
			"Modify Database User Permissions",
		]
		job: DF.Link | None
		reason: DF.SmallText | None
		site: DF.Link
		team: DF.Link | None
	# end: auto-generated types

	dashboard_fields = ("action", "reason", "site", "job")

	def after_insert(self):
		if self.action == "Login as Administrator" and self.reason:
			d = jingrow.get_all("Site", {"name": self.site}, ["notify_email", "team"])[0]
			recipient = d.notify_email or jingrow.get_pg("Team", d.team).user
			if recipient:
				team = jingrow.get_pg("Team", d.team)
				team.notify_with_email(
					[recipient],
					subject="Administrator login to your site",
					template="admin_login",
					args={"site": self.site, "user": self.owner, "reason": self.reason},
					reference_pagetype=self.pagetype,
					reference_name=self.name,
				)


def log_site_activity(site, action, reason=None, job=None):
	return jingrow.get_pg(
		{"pagetype": "Site Activity", "site": site, "action": action, "reason": reason, "job": job}
	).insert()
