package com.atlassian.bitbucket.mesh.util;

import com.atlassian.bitbucket.mesh.credentials.Credentials;
import com.atlassian.bitbucket.mesh.credentials.PrivateKeyCredentials;
import com.atlassian.bitbucket.mesh.credentials.UsernamePasswordCredentials;
import com.atlassian.bitbucket.mesh.junit.LogListener;
import org.junit.Rule;
import org.junit.Test;

import java.net.URISyntaxException;
import java.nio.file.Paths;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class UrlUtilsTest {

    @Rule
    public final LogListener logListener = new LogListener(UrlUtils.class);

    @Test
    public void testMaybeSetUserInfoWithInvalidUrl() {
        //All other cases are handled the same as setUserInfo, so they're not re-tested here
        assertEquals("this isn't a valid URL", UrlUtils.maybeSetUserInfo("this isn't a valid URL", "git"));
        logListener.assertWarn("Could not set user in URL");
    }

    @Test
    public void testMaybeSetUserInfoWithNullCredentials() {
        //Verify the existing user info is not removed
        assertEquals("http://user@localhost", UrlUtils.maybeSetUserInfo("http://user@localhost", (Credentials) null));
    }

    @Test
    public void testMaybeSetUserInfoWithPublicKeyCredentials() {
        Credentials credentials = new PrivateKeyCredentials.Builder("user", Paths.get("nonexistent")).build();
        assertEquals("http://user@localhost", UrlUtils.maybeSetUserInfo("http://admin@localhost", credentials));
    }

    @Test
    public void testMaybeSetUserInfoWithUsernamePasswordCredentials() {
        Credentials credentials = new UsernamePasswordCredentials("user", "baz");
        assertEquals("http://user@localhost", UrlUtils.maybeSetUserInfo("http://admin@localhost", credentials));
    }

    @Test
    public void testSetUserInfo() throws Exception {
        assertNull(UrlUtils.setUserInfo(null, null));
        assertNull(UrlUtils.setUserInfo(null, "git"));
        assertEquals("ssh://localhost", UrlUtils.setUserInfo("ssh://localhost", null));
        assertEquals("ssh://git@localhost", UrlUtils.setUserInfo("ssh://git@localhost", null));
        assertEquals("ssh://git@localhost", UrlUtils.setUserInfo("ssh://localhost", "git"));
        assertEquals("ssh://git@localhost/", UrlUtils.setUserInfo("ssh://localhost/", "git"));
        assertEquals("http://user@localhost", UrlUtils.setUserInfo("http://admin@localhost", "user"));
    }

    @Test(expected = URISyntaxException.class)
    public void testSetUserInfoThrowsOnInvalidUrl() throws Exception {
        UrlUtils.setUserInfo("this isn't a valid URL", "foo");
    }
}