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

import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.nav.NavBuilder;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.ContextProvider;
import com.google.common.collect.ImmutableMap;

import java.util.Map;

/**
 * Context provider for rendering the Add SSH Key prompt in the clone dialog UI.
 *
 * @since 3.11
 */
public class SshClonePromptContextProvider implements ContextProvider {

    private final AuthenticationContext authenticationContext;
    private final NavBuilder navBuilder;

    public SshClonePromptContextProvider(AuthenticationContext authenticationContext,
                                         NavBuilder navBuilder) {
        this.authenticationContext = authenticationContext;
        this.navBuilder = navBuilder;
    }

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

    @Override
    public Map<String, Object> getContextMap(Map<String, Object> context) {
        ApplicationUser user = authenticationContext.getCurrentUser();
        if (user != null) {
            NavBuilder.PathBuilder<NavBuilder.PluginServlets> path = navBuilder.pluginServlets()
                    .path("ssh", "account", "keys", "add");

            Repository repository = (Repository) context.get("repository");
            if (repository != null) {
                String repositoryUrl = navBuilder.repo(repository).buildRelative();
                path.withParam("next", repositoryUrl);
            }
            String addKeyUrl = path.buildAbsolute();

            ImmutableMap.Builder<String, Object> mb = ImmutableMap.<String, Object>builder()
                    .put("addKeyUrl", addKeyUrl);

            return mb.build();
        } else {
            return context;
        }
    }

}
