import io
from collections import Counter

import pyasn

from asncounter import CollectionsRecorder, LineCollector, TcpdumpLineCollector, args


def test_line_collectors() -> None:
    # required for lookups operations, should probably be moved to the recorder
    args.no_asn = False
    args.no_prefixes = False
    args.no_resolve_asn = True
    args.top = 10
    recorder = CollectionsRecorder()
    # test for division by zero
    recorder.display_results()
    # this uses AS64496 from RFC5398, 192.0.2.0/24 and 203.0.113.0/24
    # from RFC5737, and 2001:DB8::/32 from RFC3849
    recorder.asndb = pyasn.pyasn(
        None,
        ipasn_string="""\
192.0.2.0/24\t64496
2001:DB8::/48\t64496
2001:DB8:1::/48\t64497
""",
    )
    stream = io.StringIO(
        """\
192.0.2.1
192.0.2.2
203.0.113.42
2001:DB8::1
2001:DB8:1::1
2001:DB8:2::1
# comment

garbage
""",
    )
    collector = LineCollector(recorder=recorder)
    collector.collect(stream)
    assert recorder.asn_counter == Counter({None: 2, 64496: 3, 64497: 1})
    assert recorder.prefix_counter == Counter(
        {None: 2, "192.0.2.0/24": 2, "2001:db8:1::/48": 1, "2001:db8::/48": 1}
    )
    stream = io.StringIO(
        "10:41:33.342516 IP 192.0.2.3.65278 > 192.0.2.255.59387: UDP, length 42\n",
    )
    collector = TcpdumpLineCollector(recorder=recorder)
    collector.collect(stream)
    assert recorder.asn_counter == Counter({None: 2, 64496: 4, 64497: 1})
    assert recorder.prefix_counter == Counter(
        {None: 2, "192.0.2.0/24": 3, "2001:db8:1::/48": 1, "2001:db8::/48": 1}
    )
    recorder.display_results()
    assert recorder.asn_prefixes(64496) == {"192.0.2.0/24", "2001:db8::/48"}
    assert recorder.asn_prefixes(64496, 64497) == {
        "192.0.2.0/24",
        "2001:db8::/48",
        "2001:db8:1::/48",
    }


def test_parse_tcpdump():
    examples = [
        ("garbage", None),
        (
            "19:05:02.229065 IP 203.0.113.42.443 > 216.90.108.31.62122: tcp 60",
            "203.0.113.42",
        ),
        (
            "19:05:02.229065 IP6 2001:DB8::1.443 > 2001:DB8::2.62122: tcp 60",
            "2001:DB8::1",
        ),
        (
            "14:44:58.275872 IP [total length 52 > length 44] (invalid) 111.88.85.34.46277 > 116.202.120.165.443: tcp 0",  # noqa: E501
            "111.88.85.34",
        ),
    ]
    c = TcpdumpLineCollector(recorder=lambda x, y: None)
    for sample, result in examples:
        assert c.parse(sample) == result
