package com.atlassian.bitbucket.web.conditions;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;
import com.atlassian.bitbucket.project.ProjectService;
import com.atlassian.bitbucket.util.Page;
import com.atlassian.bitbucket.util.PageRequestImpl;

import java.util.Map;

/**
 * A condition which checks if there are no projects
 */
public class NoProjectsExistCondition implements Condition {

    static final String PROJECT_PAGE = "projectPage";

    private final ProjectService projectService;

    public NoProjectsExistCondition(ProjectService projectService) {
        this.projectService = projectService;
    }

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

    @Override
    public boolean shouldDisplay(Map<String, Object> context) {
        if (context.containsKey(PROJECT_PAGE)) {
            final Object projectPage = context.get(PROJECT_PAGE);
            return projectPage instanceof Page && ((Page) projectPage).getSize() == 0;
        } else {
            return projectService.findAll(new PageRequestImpl(0, 1)).getSize() == 0;
        }
    }
}
