package com.atlassian.bitbucket.internal.stp;

import com.atlassian.bitbucket.permission.PermissionService;
import com.atlassian.bitbucket.project.Project;
import com.atlassian.bitbucket.project.ProjectService;
import com.atlassian.bitbucket.util.*;
import com.atlassian.support.tools.spi.RootLevelSupportInfoAppender;
import com.atlassian.support.tools.spi.SupportInfoBuilder;

/**
 * Adds information about the projects to STP.
 *
 * @since 2.5
 */
public class ProjectsSupportInfo extends RootLevelSupportInfoAppender {

    private final PermissionService permissionService;
    private final ProjectService projectService;

    public ProjectsSupportInfo(PermissionService permissionService, ProjectService projectService) {
        this.permissionService = permissionService;
        this.projectService = projectService;
    }

    @Override
    protected void addSupportInfo(SupportInfoBuilder builder) {
        Iterable<Project> projects = new PagedIterable<>(request -> {
            return PageUtils.asPageOf(Project.class, projectService.findAll(request));
        }, 500);

        for (Project project : projects) {
            SupportInfoBuilder projectBuilder = builder.addCategory(StpKeys.PROJECT);
            projectBuilder.addValue(StpKeys.PROJECT_ID, Integer.toString(project.getId()));
            projectBuilder.addValue(StpKeys.PROJECT_KEY, project.getKey());
            projectBuilder.addValue(StpKeys.PROJECT_NAME, project.getName());
            projectBuilder.addValue(StpKeys.PROJECT_DESCRIPTION, project.getDescription());
            projectBuilder.addValue(StpKeys.PROJECT_MARKED_AS_PUBLIC, Boolean.toString(project.isPublic()));
            projectBuilder.addValue(StpKeys.PROJECT_IS_PUBLIC, Boolean.toString(permissionService.isPubliclyAccessible(project)));
            projectBuilder.addContext(project);
        }
    }
}
