from odoo.tests.common import TransactionCase

from odoo.addons.queue_job.job import Job


class TestQueueJobGroup(TransactionCase):
    def test_batch(self):
        self.cr.execute("delete from queue_job")
        batch = self.env["queue.job.batch"].get_new_batch("TEST")
        self.assertFalse(batch.job_ids)
        model = self.env["test.queue.job"].with_context(job_batch=batch)
        job_1 = model.with_delay().testing_method()
        self.assertEqual(job_1.db_record().state, "pending")
        job_2 = model.with_delay().testing_method()
        self.assertEqual(job_2.db_record().state, "pending")
        batch.invalidate_recordset()
        jobs = job_1.db_record()
        jobs |= job_2.db_record()
        self.assertEqual(jobs, batch.job_ids)
        batch.set_read()
        self.assertTrue(batch.is_read)
        self.assertEqual(batch.state, "draft")
        self.assertEqual(job_2.state, "pending")
        self.assertEqual(job_2.state, "pending")
        batch.enqueue()
        self.assertEqual(batch.state, "enqueued")
        self.assertEqual(job_2.state, "pending")
        self.assertEqual(job_2.state, "pending")
        job_domain = [
            ("uuid", "!=", job_1.uuid),
            ("uuid", "!=", job_2.uuid),
        ]
        update = self.env["queue.job"].search(job_domain)
        self.assertFalse(update)
        job = Job.load(self.env, job_1.uuid)
        job.perform()
        job.set_done()
        job.store()
        update = self.env["queue.job"].search(job_domain)
        self.assertTrue(update)
        self.assertEqual(1, len(update))
        job = Job.load(self.env, update.uuid)
        job.perform()
        job.set_done()
        job.store()
        batch.invalidate_recordset()
        self.assertEqual(batch.state, "progress")
        self.assertEqual(batch.completeness, 0.5)
        job_domain.append(("uuid", "!=", update.uuid))
        update = self.env["queue.job"].search(job_domain)
        self.assertFalse(update)
        job = Job.load(self.env, job_2.uuid)
        job.perform()
        job.set_done()
        job.store()
        update = self.env["queue.job"].search(job_domain)
        self.assertTrue(update)
        self.assertEqual(1, len(update))
        job = Job.load(self.env, update.uuid)
        job.perform()
        job.set_done()
        job.store()
        batch.invalidate_recordset()
        self.assertEqual(batch.state, "finished")
        self.assertEqual(batch.completeness, 1)
        self.assertFalse(batch.is_read)
