package com.atlassian.stash.internal.scm.protocol.http;

import com.atlassian.plugin.PluginAccessor;
import com.atlassian.plugin.spring.AvailableToPlugins;
import com.atlassian.bitbucket.nav.NavBuilder;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.ScmUrlFormatter;
import com.atlassian.bitbucket.scm.http.HttpScmProtocol;
import com.atlassian.bitbucket.scm.http.HttpScmRequestHandlerModuleDescriptor;
import com.atlassian.bitbucket.scm.protocol.AbstractPluginScmProtocol;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import com.atlassian.bitbucket.user.ApplicationUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * @since 3.4
 */
@AvailableToPlugins(HttpScmProtocol.class)
@Component("httpScmProtocol")
public class PluginHttpScmProtocol
        extends AbstractPluginScmProtocol<HttpScmRequestHandlerModuleDescriptor>
        implements HttpScmProtocol {

    public static final String HTTP = "http";

    private final ApplicationPropertiesService applicationPropertiesService;
    private final NavBuilder navBuilder;

    @Autowired
    public PluginHttpScmProtocol(ApplicationPropertiesService applicationPropertiesService, NavBuilder navBuilder,
                                 PluginAccessor pluginAccessor, ScmUrlFormatter urlFormatter) {
        super(pluginAccessor, urlFormatter);

        this.applicationPropertiesService = applicationPropertiesService;
        this.navBuilder = navBuilder;
    }

    @Override
    public String getCloneUrl(@Nonnull Repository repository, @Nullable ApplicationUser user) {
        return applicationPropertiesService.isHttpScmHostingEnabled() ? super.getCloneUrl(repository, user) : null;
    }

    @Nonnull
    @Override
    public String getName() {
        return HTTP;
    }

    @Nonnull
    @Override
    protected String getBaseUrl() {
        return navBuilder.buildBaseUrl() + "/scm";
    }
}
