from collections.abc import Callable

import jingrow
from jingrow.model import child_table_fields
from jingrow.tests.utils import JingrowTestCase


class TestChildTable(JingrowTestCase):
	def tearDown(self) -> None:
		try:
			jingrow.delete_pg("PageType", self.pagetype_name, force=1)
		except Exception:
			pass

	def test_child_table_pagetype_creation_and_transitioning(self) -> None:
		"""
		This method tests the creation of child table pagetype
		as well as it's transitioning from child table to normal and normal to child table pagetype
		"""

		self.pagetype_name = "Test Newy Child Table"

		try:
			pg = jingrow.get_pg(
				{
					"pagetype": "PageType",
					"name": self.pagetype_name,
					"istable": 1,
					"custom": 1,
					"module": "Integrations",
					"fields": [
						{"label": "Some Field", "fieldname": "some_fieldname", "fieldtype": "Data", "reqd": 1}
					],
				}
			).insert(ignore_permissions=True)
		except Exception:
			self.fail("Not able to create Child Table Pagetype")

		for column in child_table_fields:
			self.assertTrue(jingrow.db.has_column(self.pagetype_name, column))

		# check transitioning from child table to normal pagetype
		pg.istable = 0
		try:
			pg.save(ignore_permissions=True)
		except Exception:
			self.fail("Not able to transition from Child Table Pagetype to Normal Pagetype")

		self.check_valid_columns(self.assertFalse)

		# check transitioning from normal to child table pagetype
		pg.istable = 1
		try:
			pg.save(ignore_permissions=True)
		except Exception:
			self.fail("Not able to transition from Normal Pagetype to Child Table Pagetype")

		self.check_valid_columns(self.assertTrue)

	def check_valid_columns(self, assertion_method: Callable) -> None:
		valid_columns = jingrow.get_meta(self.pagetype_name).get_valid_columns()
		for column in child_table_fields:
			assertion_method(column in valid_columns)
