import tempfile
from pathlib import Path
from p2p.peer_store import PeerRecord, PeerStore


class TestPeerStore:
    def _s(self, t):
        return PeerStore(Path(t) / "peers.json")

    def test_crud(self):
        with tempfile.TemporaryDirectory() as t:
            s = self._s(t)
            s.save(PeerRecord(peer_id="p2p:a", alias="A", description="test"))
            assert s.get("p2p:a").alias == "A"
            assert s.get("p2p:a").description == "test"
            assert len(s) == 1
            s.remove("p2p:a")
            assert len(s) == 0

    def test_persist(self):
        with tempfile.TemporaryDirectory() as t:
            self._s(t).save(PeerRecord(peer_id="p2p:b", alias="B"))
            assert self._s(t).get("p2p:b").alias == "B"

    def test_update(self):
        with tempfile.TemporaryDirectory() as t:
            s = self._s(t)
            s.save(PeerRecord(peer_id="p2p:c", trust_level=1))
            s.update_trust("p2p:c", 3)
            s.update_description("p2p:c", "desc")
            s.update_last_seen("p2p:c")
            r = s.get("p2p:c")
            assert r.trust_level == 3
            assert r.description == "desc"
            assert r.last_seen > 0
