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

import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.ssh.SshScmProtocol;
import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.ContextProvider;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;

import java.util.Map;

/**
 * Simple context for rendering the SSH clone URL in the UI.
 *
 * @since 1.1
 */
public class SshCloneUrlContextProvider implements ContextProvider {

    private final AuthenticationContext authenticationContext;
    private final SshScmProtocol protocol;

    public SshCloneUrlContextProvider(AuthenticationContext authenticationContext, SshScmProtocol protocol) {
        this.authenticationContext = authenticationContext;
        this.protocol = protocol;
    }

    @Override
    public Map<String, Object> getContextMap(Map<String, Object> context) {
        Repository repository = (Repository) context.get("repository");
        String cloneUrl = protocol.getCloneUrl(repository, authenticationContext.getCurrentUser());

        return ImmutableMap.of("cloneUrl", MoreObjects.<Object>firstNonNull(cloneUrl, "Unavailable"));
    }

    @Override
    public void init(Map<String, String> params) throws PluginParseException {
    }
}
