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

import jingrow
from jingrow.model.page import Page


class AppUserReview(Page):
	def after_insert(self):
		self.update_average_rating()

	def update_average_rating(self):
		ratings = jingrow.db.get_all(
			"App User Review",
			filters={"app": self.app},
			fields=["rating"],
			pluck="rating",
		)

		if ratings:
			average_rating = (sum(ratings) / len(ratings)) * 5
			average_rating = round(average_rating, 2)

			jingrow.db.set_value(
				"Marketplace App", self.app, "average_rating", average_rating, update_modified=False
			)
		else:
			jingrow.db.set_value(
				"Marketplace App", self.app, "average_rating", 0, update_modified=False
			)
