package net.ilexiconn.magister.adapter;

import com.google.gson.*;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import net.ilexiconn.magister.adapter.type.RowTypeAdapter;
import net.ilexiconn.magister.cache.ContainerCache;
import net.ilexiconn.magister.container.Appointment;
import net.ilexiconn.magister.container.Grade;
import net.ilexiconn.magister.container.type.RowType;
import net.ilexiconn.magister.util.LogUtil;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

public class GradeAdapter extends TypeAdapter<Grade[]> {
    public Gson gson = new GsonBuilder()
            .registerTypeAdapter(RowType.class, new RowTypeAdapter())
            .create();

    public void write(JsonWriter out, Grade[] value) throws IOException {
        throw new UnsupportedOperationException("Not implemented");
    }

    public Grade[] read(JsonReader in) throws IOException {
        JsonObject object = gson.getAdapter(JsonElement.class).read(in).getAsJsonObject();
        JsonArray array = object.get("Items").getAsJsonArray();
        List<Grade> gradeList = new ArrayList<Grade>();
        for (JsonElement element : array) {
            JsonObject object1 = element.getAsJsonObject();
            int id = object1.get("CijferId").getAsInt();
            if (ContainerCache.has("grade-" + id, Grade.class)) {
                gradeList.add(ContainerCache.get("grade-" + id, Grade.class));
            } else {
                Grade grade = gson.fromJson(object1, Grade.class);
                try {
                    grade.filledInDate = Appointment.appointmentDateToDate(grade.filledInDateString);
                } catch (ParseException e) {
                    LogUtil.printError("Unable to parse date", e);
                }
                ContainerCache.add(grade);
                gradeList.add(grade);
            }
        }
        return gradeList.toArray(new Grade[gradeList.size()]);
    }
}

@@ -1573,16 +1573,76 @@
 class);%0A
+                if (grade.filledInDateString != null) %7B%0A    
         
@@ -1655,16 +1655,20 @@
   try %7B%0A
+    
         
@@ -1777,16 +1777,20 @@
         
+    
 %7D catch 
@@ -1830,16 +1830,20 @@
         
+   
+ 
 LogUtil.
@@ -1877,24 +1877,46 @@
  date%22, e);%0A
+                    %7D%0A
             

Fix for NPE