# Copyright (c) 2022, JINGROW and Contributors
# See license.txt

import time
import typing

import jingrow
from jingrow.tests.utils import JingrowTestCase, timeout
from jingrow.utils.background_jobs import get_queue

if typing.TYPE_CHECKING:
	from rq.job import Job


class TestSubmissionQueue(JingrowTestCase):
	queue = get_queue(qtype="default")

	@timeout(seconds=20)
	def check_status(self, job: "Job", status, wait=True):
		if wait:
			while True:
				if job.is_queued or job.is_started:
					time.sleep(0.2)
				else:
					break
		self.assertEqual(jingrow.get_pg("RQ Job", job.id).status, status)

	def test_queue_operation(self):
		from jingrow.core.pagetype.pagetype.test_pagetype import new_pagetype
		from jingrow.core.pagetype.submission_queue.submission_queue import queue_submission

		if not jingrow.db.table_exists("Test Submission Queue", cached=False):
			pg = new_pagetype("Test Submission Queue", is_submittable=True, queue_in_background=True)
			pg.insert()

		d = jingrow.new_pg("Test Submission Queue")
		d.update({"some_fieldname": "Random"})
		d.insert()

		jingrow.db.commit()
		queue_submission(d, "submit")
		jingrow.db.commit()

		# Waiting for execution
		time.sleep(4)
		submission_queue = jingrow.get_last_pg("Submission Queue")

		# Test queueing / starting
		job = self.queue.fetch_job(submission_queue.job_id)
		# Test completion
		self.check_status(job, status="finished")
