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.bitbucket.AuthorisationException;
import com.atlassian.stash.internal.notification.usersettings.UserNotificationSettings;
import com.atlassian.stash.internal.notification.usersettings.UserNotificationSettingsService;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.sun.jersey.spi.resource.Singleton;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

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

    private final UserNotificationSettingsService userNotificationSettingsService;
    private final AuthenticationContext authenticationContext;

    public UserNotificationSettingsResource(UserNotificationSettingsService userNotificationSettingsService, AuthenticationContext authenticationContext) {
        this.userNotificationSettingsService = userNotificationSettingsService;
        this.authenticationContext = authenticationContext;
    }

    @GET
    public Response getUserSettingsForCurrentUser() {
        return getUserSettings(authenticationContext.getCurrentUser());
    }

    @GET
    @Path("{userSlug}")
    public Response getUserSettings(@Context ApplicationUser user) {
        try {
            UserNotificationSettings settings = userNotificationSettingsService.getSettingsForUser(user);
            return ResponseFactory.ok(RestUserNotificationSettings.REST_TRANSFORM.apply(settings)).build();
        } catch (AuthorisationException e) {
            return ResponseFactory.noContent().status(Response.Status.FORBIDDEN).build();
        }
    }

    @PUT
    public Response updateUserSettingsForCurrentUser(RestUserNotificationSettings update) {
        return updateUserSettings(authenticationContext.getCurrentUser(), update);
    }

    @PUT
    @Path("{userSlug}")
    public Response updateUserSettings(@Context ApplicationUser user, RestUserNotificationSettings update) {
        UserNotificationSettings.Builder builder = new UserNotificationSettings.Builder();

        if (update.getSendMode() != null) {
            builder.sendMode(update.getSendMode());
        }

        try {
            userNotificationSettingsService.updateSettingsForUser(user, builder.build());
            return ResponseFactory.noContent().build();
        } catch (AuthorisationException e) {
            return ResponseFactory.noContent().status(Response.Status.FORBIDDEN).build();
        }
    }
}
