# Copyright (c) 2015, XhiveFramework Technologies and contributors
# License: MIT. See LICENSE

import xhiveframework
from xhiveframework.model.document import Document
from xhiveframework.query_builder import Interval
from xhiveframework.query_builder.functions import Now


class ErrorLog(Document):
	# 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 xhiveframework.types import DF

		error: DF.Code | None
		method: DF.Data | None
		reference_doctype: DF.Link | None
		reference_name: DF.Data | None
		seen: DF.Check
		trace_id: DF.Data | None

	# end: auto-generated types
	def onload(self):
		if not self.seen and not xhiveframework.flags.read_only:
			self.db_set("seen", 1, update_modified=0)
			xhiveframework.db.commit()

	@staticmethod
	def clear_old_logs(days=30):
		table = xhiveframework.qb.DocType("Error Log")
		xhiveframework.db.delete(table, filters=(table.modified < (Now() - Interval(days=days))))


@xhiveframework.whitelist()
def clear_error_logs():
	"""Flush all Error Logs"""
	xhiveframework.only_for("System Manager")
	xhiveframework.db.truncate("Error Log")
