package com.atlassian.bitbucket.web.conditions;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.repository.RepositoryCloneLinksRequest;
import com.atlassian.bitbucket.repository.RepositoryService;
import com.atlassian.bitbucket.permission.PermissionService;
import com.atlassian.bitbucket.util.NamedLink;

import java.util.Map;
import java.util.Set;

/**
 * A condition which checks whether the current user is able to clone the current repository.
 */
public class CanCloneRepositoryCondition implements Condition {

    private final PermissionService permissionService;
    private final RepositoryService repositoryService;

    public CanCloneRepositoryCondition(PermissionService permissionService,
                                       RepositoryService repositoryService) {
        this.permissionService = permissionService;
        this.repositoryService = repositoryService;
    }

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

    @Override
    public boolean shouldDisplay(Map<String, Object> context) {
        // Get repository and current user from contexts
        Repository repository = (Repository) context.get("repository");

        // If no repository in context, return false
        if (repository == null) {
            return false;
        }

        // If current user cannot access the current repository, they cannot clone
        if (!permissionService.isRepositoryAccessible(repository)) {
            return false;
        }

        // Check there exists at least one enabled clone protocol the current user can use
        RepositoryCloneLinksRequest cloneLinksRequest = new RepositoryCloneLinksRequest.Builder()
                .repository(repository)
                .build();
        Set<NamedLink> cloneUrls = repositoryService.getCloneLinks(cloneLinksRequest);
        return !cloneUrls.isEmpty();
    }
}
