package valandur.webapi.servlet;

import org.eclipse.jetty.http.HttpMethod;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.Sponge;
import valandur.webapi.WebAPI;
import valandur.webapi.api.servlet.BaseServlet;
import valandur.webapi.api.servlet.Endpoint;
import valandur.webapi.api.servlet.Servlet;
import valandur.webapi.servlet.base.ServletData;

import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Servlet(basePath = "registry")
public class RegistryServlet extends BaseServlet {

    private Map<Class<? extends CatalogType>, Collection<? extends CatalogType>> registryCache = new ConcurrentHashMap<>();

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

            if (registryCache.containsKey(type)) {
                data.addData("ok", true, false);
                data.addData("types", registryCache.get(type), false);
                return;
            }

            Optional<Collection<? extends CatalogType>> optTypes = WebAPI.runOnMain(() -> Sponge.getRegistry().getAllOf(type));
            optTypes.map(types -> registryCache.put(type, types));

            data.addData("ok", optTypes.isPresent(), false);
            data.addData("types", optTypes.orElse(null), false);
        } catch (ClassNotFoundException e) {
            data.sendError(HttpServletResponse.SC_NOT_FOUND, "Class " + className + " could not be found");
        }
    }
}

@@ -308,32 +308,85 @@
 ervlet.Servlet;%0A
+import valandur.webapi.cache.misc.CachedCatalogType;%0A
 import valandur.
@@ -418,16 +418,16 @@
 etData;%0A
-
 %0Aimport 
@@ -590,16 +590,88 @@
 HashMap;
+%0Aimport java.util.function.Function;%0Aimport java.util.stream.Collectors;
 %0A%0A@Servl
@@ -801,34 +801,30 @@
  Collection%3C
-? extends 
+Cached
 CatalogType%3E
@@ -1575,26 +1575,22 @@
 lection%3C
-? extends 
+Cached
 CatalogT
@@ -1633,110 +1633,312 @@
  -%3E 
-Sponge.getRegistry().getAllOf(type));%0A            optTypes.map(types -%3E registryCache.put(type, types)
+%7B%0A                Collection%3CCachedCatalogType%3E coll = Sponge.getRegistry().getAllOf(type).stream()%0A                        .map(t -%3E new CachedCatalogType(t))%0A                        .collect(Collectors.toList());%0A                registryCache.put(type, coll);%0A                return coll;%0A            %7D
 );%0A%0A

Fix registry servlet causing errors with certain mods. Fixes #60