package com.atlassian.bitbucket.web.conditions;

import com.atlassian.plugin.web.Condition;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.repository.RepositoryService;

import java.util.Map;

/**
 * A condition for detecting whether the current user has a personal fork for a given repository.
 * <p>
 * Note: Unlike {@link IsPersonalProjectCondition} and {@link IsPersonalRepositoryCondition}, this condition always
 * checks whether the current user has a personal fork of the repository and there is no mode to include forks from
 * other users.
 */
public class HasPersonalForkCondition implements Condition {

    public static final String REPOSITORY = "repository";

    private final RepositoryService repositoryService;

    public HasPersonalForkCondition(RepositoryService repositoryService) {
        this.repositoryService = repositoryService;
    }

    /**
     * Ignored, as this condition does not support any parameters for controlling its behaviour.
     *
     * @param params ignored
     */
    @Override
    public void init(Map<String, String> params) {
    }

    /**
     * Retrieves a flag indicating whether the current user has a personal fork of the repository, which is expected
     * to be present in the provided {@code context} under the key {@link #REPOSITORY "repository"}.
     *
     * @param context the context containing the repository
     * @return {@code true} if the current user has a personal fork of the context repository; otherwise, {@code false}
     */
    @Override
    public boolean shouldDisplay(Map<String, Object> context) {
        Repository repository = (Repository) context.get(REPOSITORY);

        return repository != null && repositoryService.findPersonalFork(repository) != null;
    }
}