import os

import jingrow
from jingrow.core.pagetype.data_import.data_import import export_json, import_pg
from jingrow.desk.form.save import savepgs
from jingrow.model.delete_pg import delete_pg
from jingrow.tests.utils import JingrowTestCase


class TestFixtureImport(JingrowTestCase):
	def create_new_pagetype(self, PageType: str) -> None:
		file = jingrow.get_app_path("jingrow", "custom", "fixtures", f"{PageType}.json")

		file = open(file)
		pg = file.read()
		file.close()

		savepgs(pg, "Save")

	def insert_dummy_data_and_export(self, PageType: str, dummy_name_list: list[str]) -> str:
		for name in dummy_name_list:
			pg = jingrow.get_pg({"pagetype": PageType, "member_name": name})
			pg.insert()

		path_to_exported_fixtures = os.path.join(os.getcwd(), f"{PageType}_data.json")

		export_json(PageType, path_to_exported_fixtures)

		return path_to_exported_fixtures

	def test_fixtures_import(self):
		self.assertFalse(jingrow.db.exists("PageType", "temp_pagetype"))

		self.create_new_pagetype("temp_pagetype")

		dummy_name_list = ["jhon", "jane"]
		path_to_exported_fixtures = self.insert_dummy_data_and_export("temp_pagetype", dummy_name_list)
		jingrow.db.truncate("temp_pagetype")

		import_pg(path_to_exported_fixtures)

		delete_pg("PageType", "temp_pagetype", delete_permanently=True)
		os.remove(path_to_exported_fixtures)

		self.assertEqual(jingrow.db.count("temp_pagetype"), len(dummy_name_list))

		data = jingrow.get_all("temp_pagetype", "member_name")
		jingrow.db.truncate("temp_pagetype")

		imported_data = set()
		for item in data:
			imported_data.add(item["member_name"])

		self.assertEqual(set(dummy_name_list), imported_data)

	def test_singles_fixtures_import(self):
		self.assertFalse(jingrow.db.exists("PageType", "temp_singles"))

		self.create_new_pagetype("temp_singles")

		dummy_name_list = ["Phoebe"]
		path_to_exported_fixtures = self.insert_dummy_data_and_export("temp_singles", dummy_name_list)

		singles_pagetype = jingrow.qb.PageType("Singles")
		truncate_query = (
			jingrow.qb.from_(singles_pagetype).delete().where(singles_pagetype.pagetype == "temp_singles")
		)
		truncate_query.run()

		import_pg(path_to_exported_fixtures)

		data = jingrow.db.get_single_value("temp_singles", "member_name")
		truncate_query.run()

		self.assertEqual(data, dummy_name_list[0])

		delete_pg("PageType", "temp_singles", delete_permanently=True)
		os.remove(path_to_exported_fixtures)

		jingrow.db.commit()
