package com.atlassian.bitbucket.internal.audit;

import com.atlassian.bitbucket.audit.AuditEntry;
import com.atlassian.bitbucket.audit.Channels;
import com.atlassian.bitbucket.event.audit.AuditEvent;
import com.atlassian.bitbucket.project.Project;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.event.api.EventPublisher;
import com.google.common.collect.ImmutableSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class UiAuditEventListenerTest {

    @Mock
    private InternalAuditService auditService;
    @Mock(answer = Answers.RETURNS_MOCKS)
    private AuditEvent event;
    @InjectMocks
    private UiAuditEventListener listener;

    @Test
    public void testOnEventNoChannels() throws Exception {
        when(event.getChannels()).thenReturn(ImmutableSet.<String>of());

        listener.onEvent(event);
        verifyNoMoreInteractions(auditService);
    }

    @Test
    public void testOnEventProject() throws Exception {
        when(event.getChannels()).thenReturn(ImmutableSet.of(Channels.PROJECT_UI));

        listener.onEvent(event);
        verify(auditService).save(any(Project.class), any(AuditEntry.class));
        verifyNoMoreInteractions(auditService);
    }

    @Test
    public void testOnEventRepository() throws Exception {
        when(event.getChannels()).thenReturn(ImmutableSet.of(Channels.REPOSITORY_UI));

        listener.onEvent(event);
        verify(auditService).save(any(Repository.class), any(AuditEntry.class));
        verifyNoMoreInteractions(auditService);
    }

    @Test
    public void testOnEventBoth() throws Exception {
        when(event.getChannels()).thenReturn(ImmutableSet.of(Channels.REPOSITORY_UI, Channels.PROJECT_UI));

        listener.onEvent(event);
        verify(auditService).save(any(Repository.class), any(AuditEntry.class));
        verify(auditService).save(any(Project.class), any(AuditEntry.class));
        verifyNoMoreInteractions(auditService);
    }
}
