package valandur.webapi.servlet.registry;

import org.eclipse.jetty.http.HttpMethod;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.Sponge;
import valandur.webapi.api.annotation.WebAPIEndpoint;
import valandur.webapi.api.annotation.WebAPIServlet;
import valandur.webapi.api.servlet.WebAPIBaseServlet;
import valandur.webapi.servlet.ServletData;

import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

@WebAPIServlet(basePath = "registry")
public class RegistryServlet extends WebAPIBaseServlet {

    @WebAPIEndpoint(method = HttpMethod.GET, path = "/:class", perm = "one")
    public void getRegistry(ServletData data, String className) {
        try {
            Class type = Class.forName(className);
            if (!CatalogType.class.isAssignableFrom(type)) {
                data.sendError(HttpServletResponse.SC_BAD_REQUEST, "Class must be a CatalogType");
                return;
            }

            Collection<CatalogType> types = Sponge.getRegistry().getAllOf(type);
            data.addJson("ok", true, false);
            data.addJson("types", types, false);
        } catch (ClassNotFoundException e) {
            data.sendError(HttpServletResponse.SC_NOT_FOUND, "Class " + className + " could not be found");
        }
    }
}

@@ -157,16 +157,47 @@
 Sponge;%0A
+import valandur.webapi.WebAPI;%0A
 import v
@@ -469,16 +469,112 @@
 lection;
+%0Aimport java.util.Map;%0Aimport java.util.Optional;%0Aimport java.util.concurrent.ConcurrentHashMap;
 %0A%0A@WebAP
@@ -663,16 +663,141 @@
 vlet %7B%0A%0A
+    private Map%3CClass%3C? extends CatalogType%3E, Collection%3C? extends CatalogType%3E%3E registryCache = new ConcurrentHashMap%3C%3E();%0A%0A
     @Web
@@ -963,17 +963,20 @@
   Class 
-t
+rawT
 ype = Cl
@@ -1051,17 +1051,20 @@
 bleFrom(
-t
+rawT
 ype)) %7B%0A
@@ -1200,17 +1200,16 @@
       %7D%0A
-%0A
         
@@ -1212,16 +1212,293 @@
         
+Class%3C? extends CatalogType%3E type = rawType;%0A%0A            if (registryCache.containsKey(type)) %7B%0A                data.addJson(%22ok%22, true, false);%0A                data.addJson(%22types%22, registryCache.get(type), false);%0A                return;%0A            %7D%0A%0A            Optional%3C
 Collecti
@@ -1500,16 +1500,26 @@
 lection%3C
+? extends 
 CatalogT
@@ -1526,16 +1526,43 @@
 ype%3E
- t
+%3E optT
 ypes =
+ WebAPI.runOnMain(() -%3E
  Spo
@@ -1593,16 +1593,17 @@
 Of(type)
+)
 ;%0A      
@@ -1608,39 +1608,123 @@
         
-data.addJson(%22ok%22, true
+optTypes.map(types -%3E registryCache.put(type, types));%0A%0A            data.addJson(%22ok%22, optTypes.isPresent()
 , false)
@@ -1759,21 +1759,37 @@
 types%22, 
-types
+optTypes.orElse(null)
 , false)

Add cache for registry classes. Fix possible issues with async calls. Fixes #27