import pytest

pytest.importorskip("tkinter")

from ccma.storage.repository import MemberRepository  # noqa: E402


@pytest.fixture
def repository(tmp_path):
    repository = MemberRepository(tmp_path / "store")
    repository.initialize()
    organization = repository.get_configuration()["organization"]
    organization.update({"name": "CCC Mannheim e.V.", "email": "verwaltung@example.org"})
    repository.save_organization(organization)
    return repository


def _member(repository, first_name, last_name, *, email="", status="active"):
    member = repository.create_member(
        first_name=first_name, last_name=last_name, birth_date="1990-01-01"
    )
    member.email = email
    member.status = status
    repository.save_member(member)
    return member


def test_the_dialog_preselects_reachable_live_memberships(tk_root, repository):
    from ccma.ui.data_review_mail_dialog import DataReviewMailDialog

    _member(repository, "Ada", "Lovelace", email="ada@example.org")
    _member(repository, "Grace", "Hopper", email="grace@example.org", status="ended")
    _member(repository, "Anon", "Ymous")

    dialog = DataReviewMailDialog(tk_root, repository)
    try:
        tk_root.update()
        selected = [member.display_name for member in dialog._selected_members()]

        assert selected == ["Ada Lovelace"]
        # Every member stays listed so a resigned one can still be picked by hand.
        assert len(dialog.table.get_children()) == 3
        assert "1 von 3 Mitgliedern ausgewählt" in dialog.summary_var.get()
        assert "1 Mail(s) werden erzeugt" in dialog.summary_var.get()
        assert "1 Mitglied(er) ohne E-Mail-Adresse" in dialog.warning_var.get()
    finally:
        dialog.destroy()
        tk_root.update()


def test_a_selection_without_an_address_generates_nothing(tk_root, repository, monkeypatch):
    from tkinter import messagebox

    import ccma.ui.data_review_mail_dialog as module

    _member(repository, "Anon", "Ymous")
    dialog = module.DataReviewMailDialog(tk_root, repository)
    try:
        tk_root.update()
        dialog.table.selection_set(dialog.table.get_children())
        informed = []
        monkeypatch.setattr(messagebox, "showinfo", lambda *args, **kwargs: informed.append(args))
        monkeypatch.setattr(
            module, "resolve_delivery_mode", lambda *args: pytest.fail("kein Versand erwartet")
        )

        dialog._generate()

        assert informed and "Keine Empfänger" in informed[0][0]
    finally:
        dialog.destroy()
        tk_root.update()
