# KEKS -- Python KEKS implementation
# Copyright (C) 2024-2025 Anton Rudenko <rudenko.ad@phystech.edu>
#               2024-2025 Sergey Matveev <stargrave@stargrave.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program.  If not, see <http://www.gnu.org/licenses/>.

from ipaddress import IPv6Address
from unittest import TestCase
from uuid import UUID

from hypothesis import given
from hypothesis.strategies import ip_addresses
from hypothesis.strategies import uuids

from keks import dumps
from keks import loads
from keks import NotEnoughData
from tests.strategies import junk_st


class TestUUID(TestCase):
    def test_encode(self) -> None:
        uuid_str: str = "12345678-1234-5678-1234-567812345678"
        uuid_obj: UUID = UUID(uuid_str)
        encoded: bytes = dumps(uuid_obj)
        self.assertSequenceEqual(
            encoded,
            bytes.fromhex("0412345678123456781234567812345678"),
        )

    @given(junk_st)
    def test_decode(self, junk: bytes) -> None:
        uuid_str: str = "12345678-1234-5678-1234-567812345678"
        encoded: bytes = bytes.fromhex("0412345678123456781234567812345678")
        decoded: UUID
        decoded, tail = loads(encoded + junk)
        self.assertEqual(decoded.asUUID(), UUID(uuid_str))
        self.assertSequenceEqual(tail, junk)

    def test_not_enough_data(self) -> None:
        encoded: bytes = bytes.fromhex("0412345678123456781234567812345678")
        with self.assertRaises(NotEnoughData) as err:
            loads(encoded[:-4])
        self.assertEqual(err.exception.n, 4)

    @given(uuids())
    def test_symmetric(self, u: UUID) -> None:
        decoded, _ = loads(dumps(u))
        self.assertEqual(decoded.asUUID(), u)


class TestIP(TestCase):
    @given(ip_addresses(v=6))
    def test_symmetric(self, ip: IPv6Address) -> None:
        decoded, _ = loads(dumps(ip))
        self.assertEqual(decoded.asIP(), ip)
