package com.atlassian.stash.internal.web;

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.HttpSession;

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

@RunWith(MockitoJUnitRunner.class)
public class DefaultHttpRequestInfoHelperTest {

    @Mock
    private HttpServletRequest request;

    @Test
    public void testGetRemoteAddressWithoutProxy() {
        when(request.getHeader("X-Forwarded-For")).thenReturn(null);
        when(request.getRemoteAddr()).thenReturn("2.2.2.2");

        assertEquals("2.2.2.2", new DefaultHttpRequestInfoHelper().getRemoteAddress(request));
    }

    @Test
    public void testGetRemoteAddressWithProxy() {
        when(request.getHeader("X-Forwarded-For")).thenReturn("1.1.1.1, 2.2.2.2");
        when(request.getRemoteAddr()).thenReturn("3.3.3.3");

        assertEquals("1.1.1.1,2.2.2.2,3.3.3.3", new DefaultHttpRequestInfoHelper().getRemoteAddress(request));
    }

    @Test
    public void testGetRequestUrl() {
        when(request.getRequestURI()).thenReturn("/projects");

        assertEquals("/projects", new DefaultHttpRequestInfoHelper().getRequestUrl(request));
    }

    @Test
    public void testGetRequestUrlWithContextPath() {
        when(request.getRequestURI()).thenReturn("/stash/projects");
        when(request.getContextPath()).thenReturn("/stash");

        assertEquals("/projects", new DefaultHttpRequestInfoHelper().getRequestUrl(request));
    }

    @Test
    public void testGetSessionId() {
        HttpSession session = mock(HttpSession.class);
        when(session.getId()).thenReturn("ASDG2344GHFGERY23435469BSJ465GANU0");

        when(request.getSession(eq(false))).thenReturn(session);

        String id = new DefaultHttpRequestInfoHelper().getSessionId(request);
        assertNotNull(id);

        verify(session).setAttribute(eq(DefaultHttpRequestInfoHelper.ATTR_SESSION_ID), eq(id));
    }

    @Test
    public void testGetSessionIdAgain() {
        HttpSession session = mock(HttpSession.class);
        when(session.getAttribute(eq(DefaultHttpRequestInfoHelper.ATTR_SESSION_ID))).thenReturn("ID");

        when(request.getSession(eq(false))).thenReturn(session);

        assertEquals("ID", new DefaultHttpRequestInfoHelper().getSessionId(request));
    }

    @Test
    public void testGetSessionIdWithoutSession() {
        assertNull(new DefaultHttpRequestInfoHelper().getSessionId(request));
    }
}
