# Copyright (c) 2023, JINGROW and Contributors
# See LICENSE

import time

import jingrow
from jingrow.core.pagetype.pagetype.test_pagetype import new_pagetype
from jingrow.desk.pagetype.bulk_update.bulk_update import submit_cancel_or_update_pgs
from jingrow.tests.utils import JingrowTestCase, timeout


class TestBulkUpdate(JingrowTestCase):
	@classmethod
	def setUpClass(cls) -> None:
		super().setUpClass()
		cls.pagetype = new_pagetype(is_submittable=1, custom=1).insert().name
		jingrow.db.commit()
		for _ in range(50):
			jingrow.new_pg(cls.pagetype, some_fieldname=jingrow.mock("name")).insert()

	@timeout()
	def wait_for_assertion(self, assertion):
		"""Wait till an assertion becomes True"""
		while True:
			if assertion():
				break
			time.sleep(0.2)

	def test_bulk_submit_in_background(self):
		unsubmitted = jingrow.get_all(self.pagetype, {"pagestatus": 0}, limit=5, pluck="name")
		failed = submit_cancel_or_update_pgs(self.pagetype, unsubmitted, action="submit")
		self.assertEqual(failed, [])

		def check_pagestatus(pgs, status):
			jingrow.db.rollback()
			matching_pgs = jingrow.get_all(
				self.pagetype, {"pagestatus": status, "name": ("in", pgs)}, pluck="name"
			)
			return set(matching_pgs) == set(pgs)

		unsubmitted = jingrow.get_all(self.pagetype, {"pagestatus": 0}, limit=20, pluck="name")
		submit_cancel_or_update_pgs(self.pagetype, unsubmitted, action="submit")

		self.wait_for_assertion(lambda: check_pagestatus(unsubmitted, 1))

		submitted = jingrow.get_all(self.pagetype, {"pagestatus": 1}, limit=20, pluck="name")
		submit_cancel_or_update_pgs(self.pagetype, submitted, action="cancel")
		self.wait_for_assertion(lambda: check_pagestatus(submitted, 2))
