package com.atlassian.stash.internal.notification.rest;

import com.atlassian.bitbucket.rest.util.ResponseFactory;
import com.atlassian.bitbucket.rest.util.RestUtils;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import com.atlassian.stash.internal.notification.batch.BatchNotificationJob;
import com.atlassian.bitbucket.permission.Permission;
import com.atlassian.bitbucket.permission.PermissionService;
import com.google.common.collect.ImmutableMap;
import com.sun.jersey.spi.resource.Singleton;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;

@AnonymousAllowed
@Consumes({MediaType.APPLICATION_JSON})
@Path("batch")
@Produces({RestUtils.APPLICATION_JSON_UTF8})
@Singleton
public class BatchNotificationResource {

    private final BatchNotificationJob batchNotificationJob;
    private final PermissionService permissionService;

    public BatchNotificationResource(BatchNotificationJob batchNotificationJob,
                                     PermissionService permissionService) {
        this.batchNotificationJob = batchNotificationJob;
        this.permissionService = permissionService;
    }

    @GET
    public Response getNotificationCount() {
        if (!permissionService.hasGlobalPermission(Permission.SYS_ADMIN)) {
            return ResponseFactory.status(Response.Status.UNAUTHORIZED).build();
        }

        // this is a Map in case we want to expand this endpoint at a later date
        // with more information
        Map<String, Integer> count = ImmutableMap.of("count", batchNotificationJob.notificationCount());
        return ResponseFactory.ok(count).build();
    }

    @POST
    @Path("process")
    public Response processBatchNotifications(@DefaultValue("0") @QueryParam("time") long time) {
        if (!permissionService.hasGlobalPermission(Permission.SYS_ADMIN)) {
            return ResponseFactory.status(Response.Status.UNAUTHORIZED).build();
        }

        if (time == 0) {
            batchNotificationJob.process();
        } else {
            batchNotificationJob.process(time);
        }

        return ResponseFactory.noContent().build();
    }

}
