"""Integration tests for ECMSystemSync.

Requires a running ECM server at localhost:4000.
"""

import unittest

from ecmind_blue_client.ecm import ECM
from ecmind_blue_client.ecm.definition import ECMDefinition, ECMObjectDefinition
from ecmind_blue_client.pool import SyncPoolClient
from tests._test_settings import ECM_SERVERS, ECM_USERNAME, ECM_PASSWORD


class TestECMSystemSyncIntegration(unittest.TestCase):
    """Integration tests for ECMSystemSync.definition() — requires localhost:4000."""

    @classmethod
    def setUpClass(cls):
        cls.client = SyncPoolClient(servers=ECM_SERVERS, username=ECM_USERNAME, password=ECM_PASSWORD)
        cls.ecm = ECM(cls.client)

    @classmethod
    def tearDownClass(cls):
        del cls.client

    def test_definition_returns_ecm_definition(self):
        definition = self.ecm.system.definition()

        self.assertIsInstance(definition, ECMDefinition)

    def test_definition_has_primary_language(self):
        definition = self.ecm.system.definition()

        self.assertIsNotNone(definition.primary_language)
        self.assertTrue(definition.primary_language.iso_code)

    def test_definition_cached(self):
        first = self.ecm.system.definition()
        second = self.ecm.system.definition()

        self.assertIs(first, second)

    def test_definition_force_reload(self):
        first = self.ecm.system.definition()
        reloaded = self.ecm.system.definition(force_reload=True)

        self.assertIsInstance(reloaded, ECMDefinition)
        self.assertIsNot(first, reloaded)

    def test_definition_force_reload_cached_afterwards(self):
        self.ecm.system.definition()
        reloaded = self.ecm.system.definition(force_reload=True)
        cached = self.ecm.system.definition()

        self.assertIs(reloaded, cached)

    def test_lookup_by_internal_name(self):
        definition = self.ecm.system.definition()

        obj = definition["Unittest"]

        self.assertIsInstance(obj, ECMObjectDefinition)
        self.assertEqual(obj.internal_name, "Unittest")

    def test_lookup_by_type_id(self):
        definition = self.ecm.system.definition()
        expected = definition["Unittest"]

        result = definition[expected.type_id]

        self.assertIs(result, expected)

    def test_lookup_by_internal_name_missing_raises(self):
        definition = self.ecm.system.definition()

        with self.assertRaises(KeyError):
            _ = definition["__does_not_exist__"]

    def test_lookup_by_type_id_missing_raises(self):
        definition = self.ecm.system.definition()

        with self.assertRaises(KeyError):
            _ = definition[-1]
