package com.atlassian.stash.internal.help;

import com.atlassian.bitbucket.i18n.SimpleI18nService;
import com.google.common.base.Splitter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.List;

import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;

/**
 * Created by lbain on 29/03/2016.
 */
@RunWith(MockitoJUnitRunner.class)
public class AbstractHelpPathServiceTest {
    @Spy
    private SimpleI18nService i18nService;
    private AbstractHelpPathService helpPathService;

    @Before
    public void before() {
        helpPathService = new AbstractHelpPathService() {
            @Override
            protected String getProperty(String key) {
                return i18nService.getMessage(key);
            }
        };

        when(i18nService.getMessage("bitbucket.help.prefix")).thenReturn("https://developer.atlassian.com");
    }

    @Test
    public void testGetPageUrlForNewParams() throws Exception {
        when(i18nService.getMessage("bitbucket.help.analytics.tracking")).thenReturn("utm_source=stash");
        when(i18nService.getMessage("bitbucket.help.not.a.property")).thenReturn("test");
        assertEquals("https://developer.atlassian.com/test?utm_source=stash", helpPathService.getPageUrl("bitbucket.help.not.a.property"));
    }

    @Test
    public void testGetPageUrlForAnchorAndNewParams() throws Exception {
        when(i18nService.getMessage("bitbucket.help.analytics.tracking")).thenReturn("utm_source=stash");
        when(i18nService.getMessage("bitbucket.help.not.a.property")).thenReturn("test#anchor");
        assertEquals("https://developer.atlassian.com/test?utm_source=stash#anchor", helpPathService.getPageUrl("bitbucket.help.not.a.property"));
    }

    @Test
    public void testGetPageUrlForComplexParams() throws Exception {
        when(i18nService.getMessage("bitbucket.help.analytics.tracking")).thenReturn("utm_source=stash&utm_medium=in-app-help");
        when(i18nService.getMessage("bitbucket.help.not.a.property")).thenReturn("test?id=23&utm_source=bitbucket#anchor");
        String url = helpPathService.getPageUrl("bitbucket.help.not.a.property");
        assertEquals("https://developer.atlassian.com/test", url.split("\\?")[0]);
        assertEquals("anchor", url.split("#")[1]);
        List<String> keyValues = Splitter.on('&').splitToList(url.split("\\?")[1].split("#")[0]);
        assertThat(keyValues, containsInAnyOrder("utm_medium=in-app-help", "utm_source=bitbucket", "id=23"));
    }
}