package org.limeprotocol.serialization.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.limeprotocol.Document;
import org.limeprotocol.DocumentCollection;
import org.limeprotocol.MediaType;
import org.limeprotocol.serialization.JacksonEnvelopeSerializer;
import org.limeprotocol.serialization.SerializationUtil;

import java.io.IOException;
import java.util.Iterator;

public class DocumentCollectionDeserializer extends JsonDeserializer<DocumentCollection> {


    public DocumentCollectionDeserializer() {

    }

    @Override
    public DocumentCollection deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        ObjectCodec objectCodec = jsonParser.getCodec();
        ObjectNode objectNode = objectCodec.readTree(jsonParser);
        DocumentCollection collection = new DocumentCollection();

        int total = 0;
        if (objectNode.has("total")) {
            total = objectNode.get("total").asInt();
        }
        Document[] items = new Document[total];
        MediaType itemType = MediaType.parse(objectNode.get("itemType").asText());
        ArrayNode documentsNode = (ArrayNode) objectNode.get("items");

        int i = 0;
        for (Iterator iterator = documentsNode.elements(); iterator.hasNext(); i++) {
            ObjectNode documentNode = (ObjectNode) iterator.next();
            Document document = DocumentContainerDeserializer.getDocument(documentNode, itemType, JacksonEnvelopeSerializer.getObjectMapper());
            items[i] = document;
        }

        collection.setTotal(total);
        collection.setItemType(itemType);
        collection.setItems(items);

        return collection;
    }
}
@@ -805,17 +805,16 @@
 ion%3E %7B%0A%0A
-%0A
     publ
@@ -1225,181 +1225,8 @@
 );%0A%0A
-        int total = 0;%0A        if (objectNode.has(%22total%22)) %7B%0A            total = objectNode.get(%22total%22).asInt();%0A        %7D%0A        Document%5B%5D items = new Document%5Btotal%5D;%0A
     
@@ -1374,16 +1374,79 @@
 items%22);
+%0A        Document%5B%5D items = new Document%5BdocumentsNode.size()%5D;
 %0A%0A      
@@ -1752,24 +1752,24 @@
 tMapper());%0A
-
             
@@ -1796,24 +1796,150 @@
 %0A        %7D%0A%0A
+        int total = 0;%0A        if (objectNode.has(%22total%22)) %7B%0A            total = objectNode.get(%22total%22).asInt();%0A        %7D%0A%0A
         coll

Fix DocumentCollection deserialization when total does not match items array size (total field is a pagination helper, not a counter for items array)