# Copyright (c) 2015, InfluxFramework LLC
# License: MIT. See LICENSE

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


class ErrorSnapshot(Document):
	no_feed_on_delete = True

	def onload(self):
		if not self.parent_error_snapshot:
			self.db_set("seen", True, update_modified=False)

			for relapsed in influxframework.get_all("Error Snapshot", filters={"parent_error_snapshot": self.name}):
				influxframework.db.set_value("Error Snapshot", relapsed.name, "seen", True, update_modified=False)

			influxframework.local.flags.commit = True

	def validate(self):
		parent = influxframework.get_all(
			"Error Snapshot",
			filters={"evalue": self.evalue, "parent_error_snapshot": ""},
			fields=["name", "relapses", "seen"],
			limit_page_length=1,
		)

		if parent:
			parent = parent[0]
			self.update({"parent_error_snapshot": parent["name"]})
			influxframework.db.set_value("Error Snapshot", parent["name"], "relapses", parent["relapses"] + 1)
			if parent["seen"]:
				influxframework.db.set_value("Error Snapshot", parent["name"], "seen", False)

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