package com.atlassian.stash.internal.notification.usersettings;

import com.atlassian.bitbucket.user.DummySecurityService;
import com.atlassian.bitbucket.user.ApplicationUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.*;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class BatchEmailFeatureDiscoveryTest {

    @InjectMocks
    private BatchEmailFeatureDiscovery featureDiscovery;
    @Spy
    private DummySecurityService securityService = new DummySecurityService();
    @Mock
    private UserNotificationSettingsService settingsService;
    @Mock
    private ApplicationUser user;

    @Test
    public void testShowFeatureDiscoveryNewUser() throws Exception {
        mockSettings(BatchEmailFeatureDiscovery.HIDE);
        assertFalse(featureDiscovery.shouldShowFeatureDiscovery(user));
    }

    @Test
    public void testShowFeatureDiscoveryExistingUserNeverSeen() throws Exception {
        mockSettings(Integer.MIN_VALUE);
        assertTrue(featureDiscovery.shouldShowFeatureDiscovery(user));
    }

    @Test
    public void testShowFeatureDiscoveryExistingUserSeenBefore() throws Exception {
        mockSettings(0);
        assertTrue(featureDiscovery.shouldShowFeatureDiscovery(user));
    }

    @Test
    public void testIncrementWhenNotSet() throws Exception {
        mockSettings(Integer.MIN_VALUE);
        featureDiscovery.incrementFeatureDiscoveryShowCount(user);
        expectSetValueTo(1);
    }

    @Test
    public void testIncrementWhenAlreadySet() throws Exception {
        mockSettings(1);
        featureDiscovery.incrementFeatureDiscoveryShowCount(user);
        expectSetValueTo(2);
    }

    @Test
    public void testSetNeverShowFeatureDiscovery() {
        featureDiscovery.setNeverShowFeatureDiscovery(user);
        expectSetValueTo(BatchEmailFeatureDiscovery.HIDE);
    }

    private void expectSetValueTo(int expectedValue) {
        ArgumentCaptor<UserNotificationSettings> captor = ArgumentCaptor.forClass(UserNotificationSettings.class);

        verify(settingsService).updateSettingsForUser(eq(user), captor.capture());

        UserNotificationSettings settings = captor.getValue();
        assertEquals(expectedValue, settings.getBatchFeatureDiscoveryShowCount());
    }

    private void mockSettings(int count) {
        UserNotificationSettings.Builder builder = new UserNotificationSettings.Builder();
        if (count != Integer.MIN_VALUE) { // treat Integer.MIN_VALUE as if the setting didn't exist for test purposes
            builder.batchFeatureDiscoveryShowCount(count);
        }
        when(settingsService.getSettingsForUser(user)).thenReturn(builder.build());
    }
}
