# Copyright (c) 2022, JINGROW
# License: MIT. See LICENSE

import jingrow
from jingrow.core.utils import set_timeline_pg
from jingrow.model.page import Page
from jingrow.query_builder import PageType, Interval
from jingrow.query_builder.functions import Now
from jingrow.utils import get_fullname, now, strip_html


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

		communication_date: DF.Datetime | None
		content: DF.TextEditor | None
		full_name: DF.Data | None
		ip_address: DF.Data | None
		link_pagetype: DF.Link | None
		link_name: DF.DynamicLink | None
		operation: DF.Literal["", "Login", "Logout", "Impersonate"]
		reference_pagetype: DF.Link | None
		reference_name: DF.DynamicLink | None
		reference_owner: DF.ReadOnly | None
		status: DF.Literal["", "Success", "Failed", "Linked", "Closed"]
		subject: DF.SmallText
		timeline_pagetype: DF.Link | None
		timeline_name: DF.DynamicLink | None
		user: DF.Link | None

	# end: auto-generated types
	def before_insert(self):
		self.full_name = strip_html(get_fullname(self.user))
		self.date = now()

	def validate(self):
		self.set_status()
		set_timeline_pg(self)
		self.set_ip_address()

	def set_status(self):
		if not self.is_new():
			return

		if self.reference_pagetype and self.reference_name:
			self.status = "Linked"

	def set_ip_address(self):
		if self.operation in ("Login", "Logout"):
			self.ip_address = jingrow.local.request_ip

	@staticmethod
	def clear_old_logs(days=None):
		if not days:
			days = 90
		pagetype = PageType("System Log")
		jingrow.db.delete(pagetype, filters=(pagetype.modified < (Now() - Interval(days=days))))


def on_pagetype_update():
	"""Add indexes in `tabSystem Log`"""
	jingrow.db.add_index("System Log", ["reference_pagetype", "reference_name"])
	jingrow.db.add_index("System Log", ["timeline_pagetype", "timeline_name"])


def add_authentication_log(subject, user, operation="Login", status="Success"):
	jingrow.get_pg(
		{
			"pagetype": "System Log",
			"user": user,
			"status": status,
			"subject": subject,
			"operation": operation,
		}
	).insert(ignore_permissions=True, ignore_links=True)
