package com.atlassian.stash.internal.rest.inject;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.i18n.SimpleI18nService;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.user.NoSuchUserException;
import com.atlassian.bitbucket.user.UserService;
import com.google.common.collect.ImmutableList;
import com.sun.jersey.api.core.ExtendedUriInfo;
import com.sun.jersey.api.core.HttpContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import javax.ws.rs.core.PathSegment;

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

@RunWith(MockitoJUnitRunner.class)
public class UserInjectableTest {

    private final String USER_SLUG = "t@stark";

    @Spy
    I18nService i18nService = new SimpleI18nService(SimpleI18nService.Mode.RETURN_KEYS);
    @Mock
    UserService userService;

    @InjectMocks
    UserInjectable injectable;

    @Mock
    HttpContext context;

    @Before
    public void setup() {
        ExtendedUriInfo info = mock(ExtendedUriInfo.class);
        PathSegment segment = mock(PathSegment.class);
        when(segment.getPath()).thenReturn(USER_SLUG);
        when(info.getPathSegments(eq("userSlug"))).thenReturn(ImmutableList.of(segment));
        when(context.getUriInfo()).thenReturn(info);
    }

    @Test(expected = NoSuchUserException.class)
    public void userNotFoundThrows() {
        when(userService.getUserBySlug(anyString())).thenReturn(null);
        injectable.doGetValue(context);
    }

    @Test
    public void injectableReturnsUser() {
        ApplicationUser user = mock(ApplicationUser.class);
        when(userService.getUserBySlug(eq(USER_SLUG))).thenReturn(user);

        ApplicationUser result = injectable.doGetValue(context);

        assertEquals(user, result);
        verify(userService).getUserBySlug(USER_SLUG);
        verifyNoMoreInteractions(userService);
    }
}