from nixprstatus.watchlist import Watchlist, PRInfo
from tempfile import TemporaryDirectory
import unittest

from tests.helpers.mocks import mocked_requests_get


class TestWatchlist(unittest.TestCase):
    def test_save_load(self):
        with TemporaryDirectory() as d:
            filename = f"{d}/test.json"

            watchlist = Watchlist(prs=[PRInfo(pr=1, title="PR 1")])
            watchlist.to_file(filename)

            # Check that the file was written correctly
            with open(filename, "r") as f:
                self.assertEqual(watchlist.model_dump_json(), f.read())

            # Check that the file can be read back
            loaded = Watchlist.from_file(filename)
            self.assertEqual(watchlist, loaded)

    @unittest.mock.patch("requests.get", side_effect=mocked_requests_get)
    def test_add_pr(self, mock_get):
        w = Watchlist(prs=[])
        w.add_pr(345583)
        self.assertEqual(len(w.prs), 1)
        self.assertEqual(w.prs[0].title, "wireshark: 4.2.6 -> 4.2.7")

    def test_get_pr(self):
        w = Watchlist(prs=[PRInfo(pr=1, title="PR 1")])
        self.assertEqual(w.pr(1), PRInfo(pr=1, title="PR 1"))
        self.assertEqual(w.pr(2), None)

    def test_contains(self):
        w = Watchlist(prs=[PRInfo(pr=1, title="PR 1")])
        self.assertIn(PRInfo(pr=1, title="PR 1"), w)
        self.assertIn(1, w)
        self.assertNotIn(2, w)
