package com.atlassian.stash.internal.sal;

import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.sal.api.user.UserKey;
import com.atlassian.stash.internal.i18n.LocaleHolder;
import com.atlassian.stash.internal.language.InternalLanguageService;
import com.atlassian.stash.internal.user.InternalLocaleManager;
import com.atlassian.stash.internal.user.InternalUserService;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Collections;
import java.util.Locale;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class StashLocaleResolverTest {

    private UserKey userKey = new UserKey("USER_NAME");
    @Mock
    private ApplicationUser stashUser;

    @Mock
    private InternalLanguageService languageService;
    @Mock
    private InternalLocaleManager localeManager;
    @Mock
    private LocaleHolder localeHolder;
    @Mock
    private InternalUserService userService;
    @InjectMocks
    private StashLocaleResolver resolver;

    @Test
    public void testGetLocale() {
        when(localeHolder.getLocales()).thenReturn(ImmutableList.of(Locale.CANADA, Locale.US));
        assertEquals(Locale.CANADA, resolver.getLocale());
    }

    @Test
    public void testGetLocaleWhenHolderReturnsEmptyIterable() {
        Locale systemDefault = Locale.getDefault();
        when(localeHolder.getLocales()).thenReturn(Collections.emptyList());
        assertEquals(systemDefault, resolver.getLocale());
    }

    @Test
    public void testGetLocaleWithUser() {
        when(userService.getUserByKey(userKey)).thenReturn(stashUser);

        when(localeManager.getLocale(stashUser)).thenReturn(Locale.CANADA);

        assertEquals(Locale.CANADA, resolver.getLocale(userKey));
    }

    @Test
    public void testGetLocaleWithNullUser() {
        when(userService.getUserByKey(userKey)).thenReturn(null);

        assertEquals(Locale.getDefault(), resolver.getLocale(userKey));
    }

    @Test
    public void testGetLocaleWithNullLocale() {
        when(userService.getUserByKey(userKey)).thenReturn(stashUser);

        when(localeManager.getLocale(stashUser)).thenReturn(null);

        assertEquals(Locale.getDefault(), resolver.getLocale(userKey));
    }
}
