package com.atlassian.stash.internal.web;

import com.atlassian.bitbucket.request.RequestInfoProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class HttpRequestInfoProviderTest {

    private static final String HEADER_REFERER = "http://stash.atlassian.com/login";
    private static final String HEADER_USER_AGENT = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0";

    private RequestInfoProvider provider;
    @Mock
    private HttpServletRequest request;
    @Mock
    private HttpServletResponse response;

    @Before
    public void setup() {
        provider = new DefaultHttpRequestInfoHelper().createRequestInfoProvider(request, response);
    }

    @Test
    public void testGetAction() {
        when(request.getContextPath()).thenReturn("/stash");
        when(request.getMethod()).thenReturn("GET");
        when(request.getProtocol()).thenReturn("HTTP/1.1");
        when(request.getRequestURI()).thenReturn("/stash/projects");

        assertEquals("\"GET /projects HTTP/1.1\"", provider.getAction());
    }

    @Test
    public void testGetDetails() {
        when(request.getHeader(eq("referer"))).thenReturn(HEADER_REFERER);
        when(request.getHeader(eq("user-agent"))).thenReturn(HEADER_USER_AGENT);

        assertEquals("\"" + HEADER_REFERER + "\" \"" + HEADER_USER_AGENT + "\"", provider.getDetails());
    }

    @Test
    public void testGetDetailsDefaultsHeaders() {
        assertEquals("\"\" \"\"", provider.getDetails());

        verify(request).getHeader(eq("referer"));
        verify(request).getHeader(eq("user-agent"));
    }

    @Test
    public void testGetDetailsStripsRefererQueryParameters() {
        when(request.getHeader(eq("referer"))).thenReturn(HEADER_REFERER + "?next=/projects");
        when(request.getHeader(eq("user-agent"))).thenReturn(HEADER_USER_AGENT);

        assertEquals("\"" + HEADER_REFERER + "\" \"" + HEADER_USER_AGENT + "\"", provider.getDetails());
    }

    @Test
    public void testGetProtocol() {
        when(request.getScheme()).thenReturn("HTTP/1.1");

        assertEquals("HTTP/1.1", provider.getProtocol());

        verify(request).getScheme();
    }

    @Test
    public void testGetRawRequest() {
        assertSame(request, provider.getRawRequest());
    }

    @Test
    public void testGetRawResponse() {
        assertSame(response, provider.getRawResponse());
    }

    @Test
    public void testIsSecure() {
        when(request.isSecure()).thenReturn(false, true);

        assertFalse(provider.isSecure());
        assertTrue(provider.isSecure());

        verify(request, times(2)).isSecure();
    }
}
