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


import json
from unittest.mock import MagicMock, Mock, patch

import jingrow
from jingrow.tests.utils import JingrowTestCase

from jcloud.jcloud.pagetype.agent_job.agent_job import AgentJob, 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.app_release.test_app_release import create_test_app_release
from jcloud.jcloud.pagetype.app_source.test_app_source import create_test_app_source
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
from jcloud.jcloud.pagetype.site_plan.test_site_plan import create_test_plan
from jcloud.jcloud.pagetype.site_update.site_update import SiteUpdate
from jcloud.jcloud.pagetype.subscription.test_subscription import create_test_subscription


@patch.object(SiteUpdate, "start", new=Mock())
def create_test_site_update(site: str, destination_group: str, status: str):
	return jingrow.get_pg(
		dict(pagetype="Site Update", site=site, destination_group=destination_group, status=status)
	).insert(ignore_if_duplicate=True)


class TestSiteUpdate(JingrowTestCase):
	def tearDown(self):
		jingrow.db.rollback()

	@patch.object(AgentJob, "enqueue_http_request", new=Mock())
	def test_update_of_v12_site_skips_search_index(self):
		version = "v0.2"
		app = create_test_app()
		app_source = create_test_app_source(version=version, app=app)
		group = create_test_release_group([app], jingrow_version=version)
		bench1 = create_test_bench(group=group)

		create_test_app_release(
			app_source=app_source
		)  # creates pull type release diff only but args are same

		bench2 = create_test_bench(group=group, server=bench1.server)
		self.assertNotEqual(bench1, bench2)

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

		site = create_test_site(bench=bench1.name)
		site.schedule_update()

		agent_job = jingrow.get_last_pg("Agent Job", dict(job_type=("like", "Update Site %")))
		self.assertLess(dict(skip_search_index=False).items(), json.loads(agent_job.request_data).items())

	@patch.object(AgentJob, "enqueue_http_request", new=Mock())
	def test_update_of_non_v12_site_doesnt_skip_search_index(self):
		version = "v0.3"
		app = create_test_app()
		app_source = create_test_app_source(version=version, app=app)
		group = create_test_release_group([app], jingrow_version=version)
		bench1 = create_test_bench(group=group)

		create_test_app_release(
			app_source=app_source
		)  # creates pull type release diff only but args are same

		bench2 = create_test_bench(group=group, server=bench1.server)
		self.assertNotEqual(bench1, bench2)

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

		site = create_test_site(bench=bench1.name)
		site.schedule_update()

		agent_job = jingrow.get_last_pg("Agent Job", dict(job_type=("like", "Update Site %")))
		self.assertLess(dict(skip_search_index=True).items(), json.loads(agent_job.request_data).items())

	@patch.object(AgentJob, "enqueue_http_request", new=Mock())
	def test_site_update_throws_when_destination_doesnt_have_all_the_apps_in_the_site(
		self,
	):
		app1 = create_test_app()  # jingrow
		app2 = create_test_app("app2", "App 2")
		app3 = create_test_app("app3", "App 3")

		group = create_test_release_group([app1, app2, app3])
		bench1 = create_test_bench(group=group)
		bench2 = create_test_bench(group=group, server=bench1.server)

		bench2.apps.pop()
		bench2.apps.pop()
		bench2.save()

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

		site = create_test_site(bench=bench1.name)

		self.assertRaisesRegex(
			jingrow.ValidationError,
			f".*apps installed on {site.name}: app., app.$",
			site.schedule_update,
		)

	@patch("jcloud.jcloud.pagetype.server.server.jingrow.db.commit", new=MagicMock)
	def test_site_update_callback_reallocates_workers_after_disable_maintenance_mode_job(
		self,
	):
		app1 = create_test_app()  # jingrow
		app2 = create_test_app("app2", "App 2")
		app3 = create_test_app("app3", "App 3")

		group = create_test_release_group([app1, app2, app3])
		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)
		plan = create_test_plan(site.pagetype, cpu_time=8)
		create_test_subscription(site.name, plan.name, site.team)
		site.reload()

		server = jingrow.get_pg("Server", bench1.server)
		server.disable_agent_job_auto_retry = True
		server.save()
		server.auto_scale_workers()
		bench1.reload()
		bench2.reload()
		self.assertEqual(site.bench, bench1.name)
		self.assertGreater(bench1.gunicorn_workers, 2)
		self.assertGreater(bench1.background_workers, 1)
		self.assertEqual(bench2.gunicorn_workers, 2)
		self.assertEqual(bench2.background_workers, 1)

		with fake_agent_job(
			"Update Site Pull",
			"Success",
			steps=[{"name": "Disable Maintenance Mode", "status": "Success"}],
		):
			site.schedule_update()
			poll_pending_jobs()

		bench1.reload()
		bench2.reload()
		site.reload()

		self.assertEqual(site.bench, bench2.name)
		self.assertEqual(bench1.gunicorn_workers, 2)
		self.assertEqual(bench1.background_workers, 1)
		self.assertGreater(bench2.gunicorn_workers, 2)
		self.assertGreater(bench2.background_workers, 1)
