package valandur.webapi.serialize.deserialize;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.Sponge;
import valandur.webapi.cache.misc.CachedCatalogType;

import java.io.IOException;
import java.util.Optional;

public class CachedCatalogTypeDeserializer<T extends CatalogType> extends StdDeserializer<CachedCatalogType<T>>
        implements ContextualDeserializer {

    public CachedCatalogTypeDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
        Class c = property.getType().containedType(0).getRawClass();
        return new CachedCatalogTypeDeserializer<>(c);
    }

    @Override
    public CachedCatalogType<T> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonNode tree = p.readValueAsTree();
        if (tree == null) return null;
        if (tree.path("id").isMissingNode()) return null;
        Optional<T> type = Sponge.getRegistry().getType((Class<T>) _valueClass, tree.get("id").asText());
        return type.map(CachedCatalogType::new).orElse(null);
    }
}

@@ -1308,24 +1308,26 @@
 eAsTree();%0D%0A
+%0D%0A
         if (
@@ -1339,16 +1339,31 @@
 == null)
+ %7B%0D%0A           
  return 
@@ -1381,59 +1381,333 @@
     
-if (tree.path(%22id%22).isMissingNode()) return null;%0D%0A
+%7D%0D%0A%0D%0A        if (tree.isTextual()) %7B%0D%0A            Optional%3CT%3E type = Sponge.getRegistry().getType((Class%3CT%3E) _valueClass, tree.asText());%0D%0A            return type.map(CachedCatalogType::new).orElse(null);%0D%0A        %7D else %7B%0D%0A            if (tree.path(%22id%22).isMissingNode()) %7B%0D%0A                return null;%0D%0A            %7D%0D%0A    
     
@@ -1809,32 +1809,36 @@
 xt());%0D%0A        
+    
 return type.map(
@@ -1872,22 +1872,33 @@
 lse(null);%0D%0A
+        %7D%0D%0A
     %7D%0D%0A%7D%0D%0A

Allow passing catalog types without wrapper