# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE
import copy

import jingrow
from jingrow.core.pagetype.version.version import get_diff
from jingrow.test_runner import make_test_objects
from jingrow.tests.utils import JingrowTestCase


class TestVersion(JingrowTestCase):
	def test_get_diff(self):
		jingrow.set_user("Administrator")
		test_records = make_test_objects("Event", reset=True)
		old_pg = jingrow.get_pg("Event", test_records[0])
		new_pg = copy.deepcopy(old_pg)

		old_pg.color = None
		new_pg.color = "#fafafa"

		diff = get_diff(old_pg, new_pg)["changed"]

		self.assertEqual(get_fieldnames(diff)[0], "color")
		self.assertTrue(get_old_values(diff)[0] is None)
		self.assertEqual(get_new_values(diff)[0], "#fafafa")

		new_pg.starts_on = "2017-07-20"

		diff = get_diff(old_pg, new_pg)["changed"]

		self.assertEqual(get_fieldnames(diff)[1], "starts_on")
		self.assertEqual(get_old_values(diff)[1], "01-01-2014 00:00:00")
		self.assertEqual(get_new_values(diff)[1], "07-20-2017 00:00:00")

	def test_no_version_on_new_pg(self):
		from jingrow.desk.form.load import get_versions

		t = jingrow.get_pg(pagetype="ToDo", description="something")
		t.save(ignore_version=False)

		self.assertFalse(get_versions(t))

		t = jingrow.get_pg(t.pagetype, t.name)
		t.description = "changed"
		t.save(ignore_version=False)
		self.assertTrue(get_versions(t))


def get_fieldnames(change_array):
	return [d[0] for d in change_array]


def get_old_values(change_array):
	return [d[1] for d in change_array]


def get_new_values(change_array):
	return [d[2] for d in change_array]
