# (c) cavaliba.com - test_instance_last_sync.py

from django.test import TestCase
from django.utils import timezone

import app_home.cache as cache
from app_data.data import Instance
from app_data.models import DataEAV, DataInstance
from tests import helper

AAA = {"username": "testuser", "perms": ["p_data_admin"]}


class TestLastSync(TestCase):
    def setUp(self):
        cache.clear()
        helper.add_schema(classname="lstest")

    def test_last_sync_null_on_new_instance(self):
        instance = Instance(classname="lstest")
        self.assertIsNone(instance.last_sync)

    def test_last_sync_null_after_create_without_sync(self):
        instance = Instance(classname="lstest")
        instance.merge_import({"classname": "lstest", "keyname": "obj01"}, aaa=AAA)
        instance.create()
        iobj = DataInstance.objects.get(classname="lstest", keyname="obj01")
        self.assertIsNone(iobj.last_sync)

    def test_last_sync_set_when_assigned_before_create(self):
        instance = Instance(classname="lstest")
        instance.merge_import({"classname": "lstest", "keyname": "obj02"}, aaa=AAA)
        now = timezone.now()
        instance.last_sync = now
        instance.create()
        iobj = DataInstance.objects.get(classname="lstest", keyname="obj02")
        self.assertIsNotNone(iobj.last_sync)

    def test_last_sync_not_in_data_json(self):
        instance = Instance(classname="lstest")
        instance.merge_import({"classname": "lstest", "keyname": "obj03"}, aaa=AAA)
        instance.last_sync = timezone.now()
        instance.create()
        iobj = DataInstance.objects.get(classname="lstest", keyname="obj03")
        self.assertNotIn("last_sync", iobj.data_json)

    def test_last_sync_not_in_eav(self):
        instance = Instance(classname="lstest")
        instance.merge_import({"classname": "lstest", "keyname": "obj04"}, aaa=AAA)
        instance.last_sync = timezone.now()
        instance.create()
        eav_entries = DataEAV.objects.filter(
            classname="lstest", keyname="obj04", fieldname="last_sync"
        )
        self.assertEqual(eav_entries.count(), 0)

    def test_last_sync_loaded_from_iobj(self):
        instance = Instance(classname="lstest")
        instance.merge_import({"classname": "lstest", "keyname": "obj05"}, aaa=AAA)
        now = timezone.now()
        instance.last_sync = now
        instance.create()
        loaded = Instance.from_keyname("lstest", "obj05")
        self.assertIsNotNone(loaded.last_sync)

    def test_last_update_unchanged_when_no_diff(self):
        helper.add_instance(classname="lstest", keyname="obj06")
        instance = Instance.from_keyname("lstest", "obj06")
        last_update_before = instance.iobj.last_update
        instance.merge_import({"classname": "lstest", "keyname": "obj06"}, aaa=AAA)
        instance.update()
        instance2 = Instance.from_keyname("lstest", "obj06")
        self.assertEqual(instance2.iobj.last_update, last_update_before)
