from unittest import TestCase

from amqp.adapter.data_message_factory import DataMessageFactory
from amqp.model.snowflake_id import SnowflakeId


class SnowflakeIdTest(TestCase):

    def test_equals(self):
        _id_1 = DataMessageFactory.get_instance(1).generate_snowflake_id()
        _id_2 = DataMessageFactory.get_instance(1).generate_snowflake_id()
        self.assertFalse(_id_1 == _id_2)
        _id_3 = SnowflakeId(_id_1.get_bytes())
        self.assertTrue(_id_1 == _id_3)

    def test_lt(self):
        _id_1 = DataMessageFactory.get_instance(1).generate_snowflake_id()
        _id_2 = DataMessageFactory.get_instance(1).generate_snowflake_id()
        self.assertTrue(_id_1 < _id_2)

    def test_from_hex(self):
        _factory = DataMessageFactory.get_instance(1)
        _id_1 = _factory.generate_snowflake_id()
        _id_1_ser = _id_1.as_string()
        _id_2 = SnowflakeId.from_hex(_id_1_ser)
        self.assertTrue(_id_1 == _id_2)
        with self.assertRaises(RuntimeError) as context:
            SnowflakeId.from_hex("100")
        self.assertTrue(
            f"MessageId is {SnowflakeId.SNOWFLAKE_ID_WIDTH * 8} bits wide, it is represented by HEX string "
            in str(context.exception)
        )

    def test_get_bytes(self):
        _factory = DataMessageFactory.get_instance(1)
        _id_1 = _factory.generate_snowflake_id()
        _id_1_ser = _id_1.get_bytes()
        self.assertEqual(SnowflakeId.SNOWFLAKE_ID_WIDTH, len(_id_1_ser))

    def test_get_bits(self):
        _factory = DataMessageFactory.get_instance(1)
        _id_1 = _factory.generate_snowflake_id()
        self.assertEqual(2, len(_id_1.get_bits()))

    def test_as_string(self):
        _factory = DataMessageFactory.get_instance(1)
        _id_1 = _factory.generate_snowflake_id()
        self.assertEqual(2 * SnowflakeId.SNOWFLAKE_ID_WIDTH, len(_id_1.as_string()))
