package com.atlassian.stash.internal.sal.user;

import com.atlassian.bitbucket.avatar.AvatarRequest;
import com.atlassian.bitbucket.avatar.AvatarService;
import com.atlassian.bitbucket.nav.NavBuilder;
import com.atlassian.bitbucket.user.ApplicationUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.net.URI;
import java.net.URISyntaxException;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class DefaultUserProfileTest {

    @Mock
    AvatarService avatarService;
    @Mock
    NavBuilder navBuilder;
    @Mock
    ApplicationUser user;
    @InjectMocks
    DefaultUserProfile userProfile;

    @Test
    public void testGetProfileUrl() throws URISyntaxException {
        when(user.getName()).thenReturn("tim");
        NavBuilder.Profile profile = mock(NavBuilder.Profile.class);
        when(navBuilder.user(any(ApplicationUser.class))).thenReturn(profile);
        when(profile.buildRelNoContext()).thenReturn("/users/tim");
        assertThat("URI should return user profile page",
                userProfile.getProfilePageUri(), equalTo(new URI("/users/tim")));
    }

    @Test
    public void testGetAvatar() throws URISyntaxException {
        ArgumentCaptor<AvatarRequest> requestCaptor = ArgumentCaptor.forClass(AvatarRequest.class);
        ArgumentCaptor<ApplicationUser> userCaptor = ArgumentCaptor.forClass(ApplicationUser.class);

        // with no SSL
        when(navBuilder.buildBaseUrl()).thenReturn("http://insecure.net");
        when(avatarService.getUrlForPerson(userCaptor.capture(), requestCaptor.capture())).thenReturn("http://gravatar?tim");

        assertEquals(new URI("http://gravatar?tim"), userProfile.getUrlForPerson(32));
        assertEquals(32, requestCaptor.getValue().getSize());
        assertFalse(requestCaptor.getValue().isSecure());

        // with SSL
        when(navBuilder.buildBaseUrl()).thenReturn("https://secure.net");
        when(avatarService.getUrlForPerson(userCaptor.capture(), requestCaptor.capture())).thenReturn("https://secure.gravatar?tim");

        assertEquals(new URI("https://secure.gravatar?tim"), userProfile.getUrlForPerson(128));
        assertEquals(128, requestCaptor.getValue().getSize());
        assertTrue(requestCaptor.getValue().isSecure());
    }
}
