package com.atlassian.stash.internal.web.soy.functions.nav;

import com.atlassian.plugin.webresource.UrlMode;
import com.atlassian.plugin.webresource.WebResourceUrlProvider;
import com.atlassian.bitbucket.nav.NavBuilder;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.net.URI;

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

@RunWith(MockitoJUnitRunner.class)
public class PluginResourceUrlFunctionTest {
    @Mock
    ApplicationPropertiesService applicationPropertiesService;

    @Mock
    WebResourceUrlProvider webResourceUrlProvider;

    @Mock
    NavBuilder navBuilder;

    @InjectMocks
    PluginResourceUrlFunction pluginResourceUrlFunction;

    @Test
    public void testApply() throws Exception {
        URI configuredBaseUri = new URI("http://coopers:7990/bitbucket");
        URI contextRequestBaseUri = new URI("http://localhost:7990/bitbucket");

        when(navBuilder.buildConfigured()).thenReturn(configuredBaseUri.toString());
        when(navBuilder.buildAbsolute()).thenReturn(contextRequestBaseUri.toString());

        String moduleKey = "com.atlassian.bitbucket.server.plugin.notifications:notifications-plugin";
        String resourceName = "lolcat.jpg";
        String staticResourceSuffix = "/awesome/static/resource/stuff/goes/here";

        when(webResourceUrlProvider.getStaticPluginResourceUrl(eq(moduleKey), eq(resourceName), eq(UrlMode.ABSOLUTE))).thenReturn(contextRequestBaseUri + staticResourceSuffix);
        when(webResourceUrlProvider.getStaticPluginResourceUrl(eq(moduleKey), eq(resourceName), eq(UrlMode.RELATIVE))).thenReturn(staticResourceSuffix);

        String testUrl = pluginResourceUrlFunction.apply(moduleKey, resourceName, ImmutableMap.of("urlMode", "configured"));
        assertEquals("Base URL should be replaced with configured baseUrl", testUrl, configuredBaseUri.toString() + staticResourceSuffix);

        testUrl = pluginResourceUrlFunction.apply(moduleKey, resourceName, ImmutableMap.of("urlMode", "absolute"));
        assertEquals("Base URL should be replaced with baseUrl from context request", testUrl, contextRequestBaseUri.toString() + staticResourceSuffix);

        testUrl = pluginResourceUrlFunction.apply(moduleKey, resourceName, ImmutableMap.of("urlMode", "relative"));
        assertEquals("Returned URL should be relative path with no baseUrl", testUrl, staticResourceSuffix);
    }
}
