from src.gameplay import chatWatch as chatWatchModule
from src.gameplay.chatWatch import watchChat


def _context():
    return {
        'ng_pause': False,
        'ng_screenshot': object(),
        'ng_chat': {},
    }


def test_new_tab_pauses_and_logs(mocker, monkeypatch):
    monkeypatch.delenv(chatWatchModule.CHATWATCH_ENV, raising=False)
    logSpy = mocker.patch.object(chatWatchModule, 'logEvent')
    mocker.patch.object(chatWatchModule, 'saveEventScreenshot')
    mocker.patch.object(
        chatWatchModule, 'getTabs',
        side_effect=[
            {'Default': {}, 'Local Chat': {}},
            {'Default': {}, 'Local Chat': {}, 'Unknown:2': {}},
        ])
    context = _context()

    watchChat(context)
    assert context['ng_pause'] is False

    watchChat(context)

    assert context['ng_pause'] is True
    assert logSpy.call_args[0][0] == 'chatAlert'
    assert logSpy.call_args[0][1]['newTabs'] == ['Unknown:2']


def test_no_new_tabs_no_alarm(mocker, monkeypatch):
    monkeypatch.delenv(chatWatchModule.CHATWATCH_ENV, raising=False)
    logSpy = mocker.patch.object(chatWatchModule, 'logEvent')
    mocker.patch.object(
        chatWatchModule, 'getTabs',
        return_value={'Default': {}, 'Local Chat': {}})
    context = _context()

    watchChat(context)
    watchChat(context)

    assert context['ng_pause'] is False
    logSpy.assert_not_called()


def test_disabled_via_env(mocker, monkeypatch):
    monkeypatch.setenv(chatWatchModule.CHATWATCH_ENV, '0')
    tabsSpy = mocker.patch.object(chatWatchModule, 'getTabs')

    watchChat(_context())

    tabsSpy.assert_not_called()
