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

import json
import os

import jingrow
from jingrow.tests.utils import JingrowTestCase


class TestPackage(JingrowTestCase):
	def test_package_release(self):
		make_test_package()
		make_test_module()
		make_test_pagetype()
		make_test_server_script()
		make_test_web_page()

		# make release
		jingrow.get_pg(dict(pagetype="Package Release", package="Test Package", publish=1)).insert()

		self.assertTrue(os.path.exists(jingrow.get_site_path("packages", "test-package")))
		self.assertTrue(
			os.path.exists(jingrow.get_site_path("packages", "test-package", "test_module_for_package"))
		)
		self.assertTrue(
			os.path.exists(
				jingrow.get_site_path(
					"packages",
					"test-package",
					"test_module_for_package",
					"pagetype",
					"test_pagetype_for_package",
				)
			)
		)
		with open(
			jingrow.get_site_path(
				"packages",
				"test-package",
				"test_module_for_package",
				"pagetype",
				"test_pagetype_for_package",
				"test_pagetype_for_package.json",
			)
		) as f:
			pagetype = json.loads(f.read())
			self.assertEqual(pagetype["pagetype"], "PageType")
			self.assertEqual(pagetype["name"], "Test PageType for Package")
			self.assertEqual(pagetype["fields"][0]["fieldname"], "test_field")


def make_test_package():
	if not jingrow.db.exists("Package", "Test Package"):
		jingrow.get_pg(
			dict(pagetype="Package", name="Test Package", package_name="test-package", readme="# Test Package")
		).insert()


def make_test_module():
	if not jingrow.db.exists("Module Def", "Test Module for Package"):
		jingrow.get_pg(
			dict(
				pagetype="Module Def",
				module_name="Test Module for Package",
				custom=1,
				app_name="jingrow",
				package="Test Package",
			)
		).insert()


def make_test_pagetype():
	if not jingrow.db.exists("PageType", "Test PageType for Package"):
		jingrow.get_pg(
			dict(
				pagetype="PageType",
				name="Test PageType for Package",
				custom=1,
				module="Test Module for Package",
				autoname="Prompt",
				fields=[dict(fieldname="test_field", fieldtype="Data", label="Test Field")],
			)
		).insert()


def make_test_server_script():
	if not jingrow.db.exists("Server Script", "Test Script for Package"):
		jingrow.get_pg(
			dict(
				pagetype="Server Script",
				name="Test Script for Package",
				module="Test Module for Package",
				script_type="PageType Event",
				reference_pagetype="Test PageType for Package",
				pagetype_event="Before Save",
				script='jingrow.msgprint("Test")',
			)
		).insert()


def make_test_web_page():
	if not jingrow.db.exists("Web Page", "test-web-page-for-package"):
		jingrow.get_pg(
			dict(
				pagetype="Web Page",
				module="Test Module for Package",
				main_section="Some content",
				published=1,
				title="Test Web Page for Package",
			)
		).insert()
