package com.atlassian.bitbucket.internal.ssh.service;

import com.atlassian.bitbucket.nav.NavBuilder;
import com.atlassian.bitbucket.ssh.SshConfiguration;
import com.atlassian.bitbucket.ssh.SshConfigurationService;

import javax.annotation.Nonnull;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * {@inheritDoc}
 */
public class DefaultSshBaseUrlResolver implements SshBaseUrlResolver {
    private final NavBuilder navBuilder;
    private final SshConfigurationService sshConfigurationService;

    public DefaultSshBaseUrlResolver(NavBuilder navBuilder, SshConfigurationService sshConfigurationService) {
        this.navBuilder = navBuilder;
        this.sshConfigurationService = sshConfigurationService;
    }

    @Nonnull
    @Override
    public String getBaseUrl() {
        SshConfiguration cfg = sshConfigurationService.getConfiguration();

        String baseUrl = cfg.getBaseUrl();
        if (baseUrl == null) {
            baseUrl = getDefaultBaseUrl();
        }
        return baseUrl;
    }

    @Nonnull
    @Override
    public String getDefaultBaseUrl() {
        try {
            String host = new URI(navBuilder.buildBaseUrl()).getHost();
            return String.format("ssh://%s:%s", host, sshConfigurationService.getConfiguration().getPort());
        } catch (URISyntaxException e) {
            // Should not be possible since navbuilder uses a URI to build base url
            throw new IllegalStateException("Base URL is not a valid URI");
        }
    }
}
