package com.atlassian.stash.internal.help;

import com.atlassian.bitbucket.i18n.SimpleI18nService;
import com.atlassian.stash.internal.i18n.LocaleHolder;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Locale;

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

@RunWith(MockitoJUnitRunner.class)
public class I18nHelpPathServiceTest {

    @Mock
    private LocaleHolder localeHolder;
    @Spy
    private SimpleI18nService i18nService;
    @InjectMocks
    private I18nHelpPathService service;

    @Before
    public void before() {
        setLocales();
        when(i18nService.getMessage("bitbucket.help.analytics.tracking")).thenReturn("analytics=tracking");
    }

    @Test
    public void testNoPrefixMeansNoUrl() {
        when(i18nService.getMessage("bitbucket.help.prefix")).thenReturn(null);
        assertNull(service.getPrefix());
        assertNull(service.getPageUrl("foo"));
    }

    @Test
    public void testHelpPathAttributesPresent() {
        assertEquals("bitbucket.help.prefix", service.getPrefix());
        assertEquals("foo.title", service.getPageTitle("foo"));
        assertEquals("foo.alt", service.getPageAlt("foo"));
        assertEquals("foo", service.getPageKey("foo"));
        assertEquals("bitbucket.help.prefix/foo?analytics=tracking", service.getPageUrl("foo"));
    }

    @Test
    public void testNullTopicKeys() {
        assertNull(service.getPageAlt(null));
        assertNull(service.getPageTitle(null));
        assertNull(service.getPageKey(null));
        assertNull(service.getPageUrl(null));
    }

    @Test
    public void testGetUrlShouldContainLocalesFromLocaleHolder() throws Exception {
        setLocales(Locale.FRANCE, Locale.CHINA, Locale.CANADA, Locale.GERMAN, Locale.ENGLISH);
        assertEquals("bitbucket.help.prefix/foo?analytics=tracking&locale=fr_FR%2Czh_CN", service.getPageUrl("foo"));
    }

    @Test
    public void testGetUrlShouldContainLocaleFromLocaleHolderIfOnlySingleLocale() throws Exception {
        setLocales(Locale.FRANCE);
        assertEquals("bitbucket.help.prefix/foo?analytics=tracking&locale=fr_FR", service.getPageUrl("foo"));
    }

    @Test
    public void testGetUrlShouldNotContainLocaleFromLocaleHolderIfOnlyEnglish() throws Exception {
        setLocales(Locale.ENGLISH, Locale.FRANCE);
        assertEquals("bitbucket.help.prefix/foo?analytics=tracking", service.getPageUrl("foo"));
    }

    private void setLocales(Locale... locales) {
        when(localeHolder.getLocales()).thenReturn(Lists.newArrayList(locales));
        when(localeHolder.getLocales(Matchers.<Locale[]>anyVararg())).thenReturn(Lists.newArrayList(locales));
    }

}
