# Copyright (c) 2023, JINGROW
# See license.txt

import jingrow
from jingrow.tests.utils import JingrowTestCase

from jcloud.api.notifications import get_unread_count
from jcloud.jcloud.pagetype.agent_job.agent_job import poll_pending_jobs
from jcloud.jcloud.pagetype.agent_job.test_agent_job import fake_agent_job
from jcloud.jcloud.pagetype.app.test_app import create_test_app
from jcloud.jcloud.pagetype.deploy_candidate_difference.test_deploy_candidate_difference import (
	create_test_deploy_candidate_differences,
)
from jcloud.jcloud.pagetype.release_group.test_release_group import (
	create_test_release_group,
)
from jcloud.jcloud.pagetype.site.test_site import create_test_bench, create_test_site


class TestJcloudNotification(JingrowTestCase):
	def setUp(self):
		app1 = create_test_app()  # jingrow
		app2 = create_test_app("app2", "App 2")
		app3 = create_test_app("app3", "App 3")
		self.apps = [app1, app2, app3]

	def tearDown(self):
		jingrow.db.rollback()

	def test_notification_is_created_when_agent_job_fails(self):
		group = create_test_release_group(self.apps)
		bench1 = create_test_bench(group=group)
		bench2 = create_test_bench(group=group, server=bench1.server)

		create_test_deploy_candidate_differences(
			bench2.candidate
		)  # for site update to be available

		site = create_test_site(bench=bench1.name)

		self.assertEqual(jingrow.db.count("Jcloud Notification"), 0)
		with fake_agent_job("Update Site Pull", "Failure",), fake_agent_job(
			"Recover Failed Site Update",
			"Success",
		):
			site.schedule_update()
			poll_pending_jobs()

		notification = jingrow.get_last_pg("Jcloud Notification")
		self.assertEqual(notification.type, "Site Update")
		# api test is added here since it's trivial
		# move to separate file if it gets more complex
		self.assertEqual(get_unread_count(), 1)
