import unittest
from unittest.mock import Mock, patch

import sadb.database as database
from sadb.source.flatpak import FlatpakType


class FlatpakAppStreamTests(unittest.TestCase):
    @patch("sadb.source.flatpak.Flatpak.Installation.new_system")
    def test_updates_appstream_for_each_enabled_remote(self, new_system):
        enabled = Mock()
        enabled.get_disabled.return_value = False
        enabled.get_name.return_value = "flathub"
        disabled = Mock()
        disabled.get_disabled.return_value = True

        installation = new_system.return_value
        installation.list_remotes.return_value = [enabled, disabled]

        FlatpakType.update_appstream()

        installation.update_appstream_sync.assert_called_once_with(
            "flathub", None, None
        )

    def test_database_update_refreshes_appstream_before_downloading_data(self):
        events = []
        config = Mock(verbose=False, repo_url="https://example.test/")

        with patch.object(
            FlatpakType, "update_appstream", side_effect=lambda **_kwargs: events.append("appstream")
        ), patch(
            "sadb.utilities.download_yaml",
            side_effect=lambda *_args, **_kwargs: events.append("download") or {},
        ), patch(
            "sadb.yaml_parse.get_apps_from_yaml", return_value=[]
        ), patch(
            "sadb.appstream.enrich_apps", side_effect=lambda apps: apps
        ), patch(
            "sadb.appstream_metadata.complement_flatpak_apps"
        ), patch.object(
            database, "WritableDB"
        ):
            database.update_db(config)

        self.assertEqual(events, ["appstream", "download"])


if __name__ == "__main__":
    unittest.main()
