package org.croudtrip.rest;

import com.google.common.base.Optional;

import org.croudtrip.api.account.User;
import org.croudtrip.api.gcm.GcmRegistration;
import org.croudtrip.api.gcm.GcmRegistrationDescription;
import org.croudtrip.gcm.GcmManager;

import javax.inject.Inject;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import io.dropwizard.auth.Auth;
import io.dropwizard.hibernate.UnitOfWork;

/**
 * Resource for managing user vehicles.
 */
@Path("/gcm")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class GcmRegistrationResource {

    private final GcmManager gcmManager;

    @Inject
    GcmRegistrationResource(GcmManager gcmManager) {
        this.gcmManager = gcmManager;
    }


    @PUT
    @UnitOfWork
    public GcmRegistration register(@Auth User user, @Valid GcmRegistrationDescription description) {
        return gcmManager.register(user, description);
    }


    @GET
    @UnitOfWork
    public GcmRegistration getRegistration(@Auth User user) {
        Optional<GcmRegistration> registration = gcmManager.findRegistrationByUser(user);
        if (registration.isPresent()) return registration.get();
        else throw RestUtils.createNotFoundException();
    }

}

@@ -63,16 +63,58 @@
 ional;%0A%0A
+import org.croudtrip.account.UserManager;%0A
 import o
@@ -285,16 +285,45 @@
 nager;%0A%0A
+import java.io.IOException;%0A%0A
 import j
@@ -421,18 +421,76 @@
 x.ws.rs.
-GE
+DefaultValue;%0Aimport javax.ws.rs.GET;%0Aimport javax.ws.rs.POS
 T;%0Aimpor
@@ -558,24 +558,55 @@
 s.Produces;%0A
+import javax.ws.rs.QueryParam;%0A
 import javax
@@ -738,21 +738,52 @@
 ing 
-user vehicles
+GCM registrations (and messages for testing)
 .%0A *
@@ -954,16 +954,59 @@
 Manager;
+%0A    private final UserManager userManager;
 %0A%0A    @I
@@ -1060,16 +1060,41 @@
 mManager
+, UserManager userManager
 ) %7B%0A    
@@ -1123,24 +1123,64 @@
 gcmManager;%0A
+        this.userManager = userManager;%0A
     %7D%0A%0A%0A    
@@ -1670,10 +1670,685 @@
 %0A    %7D%0A%0A
+%0A    @POST%0A    @UnitOfWork%0A    public void sendTestMessage(@QueryParam(%22userId%22) Long userId, @DefaultValue(%22hello%22) @QueryParam(%22msg%22) String message) throws IOException %7B%0A        if (userId == null) throw RestUtils.createJsonFormattedException(%22missing query param %5C%22userId%5C%22%22, 400);%0A%0A        Optional%3CUser%3E user = userManager.findUserById(userId);%0A        if (!user.isPresent()) throw RestUtils.createNotFoundException();%0A        Optional%3CGcmRegistration%3E registration = gcmManager.findRegistrationByUser(user.get());%0A        if (!registration.isPresent()) throw RestUtils.createNotFoundException();%0A%0A        gcmManager.sendGcmMessage(registration.get(), message);%0A    %7D%0A%0A
 %7D%0A

send test gcm msgs via gcm resource