package com.miguelgaeta.bootstrap.mg_preference;

import android.content.Context;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.miguelgaeta.bootstrap.mg_log.MGLog;

import java.io.FileNotFoundException;
import java.lang.reflect.Type;

import lombok.Getter;
import lombok.NonNull;

/**
 * Created by Miguel Gaeta on 9/25/15.
 */
public class MGPrefStoreTypeByeStream implements MGPrefStoreInterface {

    private Context context;

    @Getter(lazy = true)
    private final ThreadLocal<Kryo> kryos = new ThreadLocal<Kryo>() {

        protected Kryo initialValue() {

            return new Kryo();
        }
    };

    @Override
    public void init(@NonNull Context context) {

        this.context = context;
    }

    @Override
    public Object get(@NonNull String key, Type typeOfObject, boolean versioned) {


        try {
            final Input input = new Input(context.openFileInput("shared_prefs_key.bin"));

            final Object output = getKryos().get().readClassAndObject(input);

            input.close();

            return output;

        } catch (FileNotFoundException e) {

            MGLog.i(e, "File not found for key: " + key);
        }

        return null;
    }

    @Override
    public void set(@NonNull String key, Object value, Type typeOfObject, boolean versioned) {

        try {
            final Output output =
                new Output(context.openFileOutput("shared_prefs_key.bin", Context.MODE_PRIVATE));

            getKryos().get().writeClassAndObject(output, value);

            output.close();

        } catch (FileNotFoundException e) {

            MGLog.i(e, "File not found for key: " + key);
        }
    }

    @Override
    public void clear() {

        // TODO
    }
}

@@ -115,16 +115,64 @@
 o.Kryo;%0A
+import com.esotericsoftware.kryo.KryoException;%0A
 import c
@@ -298,16 +298,72 @@
 MGLog;%0A%0A
+import org.objenesis.strategy.StdInstantiatorStrategy;%0A%0A
 import j
@@ -773,25 +773,267 @@
     
-return new Kryo()
+final Kryo kryo = new Kryo();%0A%0A            // Use the default instantiation, but attempt to use JVM trickery if that fails.%0A            kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));%0A%0A            return kryo
 ;%0A  
@@ -1249,17 +1249,16 @@
 ned) %7B%0A%0A
-%0A
         
@@ -1255,32 +1255,33 @@
 %0A%0A        try %7B%0A
+%0A
             fina
@@ -1499,32 +1499,48 @@
        %7D catch (
+KryoException %7C 
 FileNotFoundExce
@@ -1571,38 +1571,45 @@
 MGLog.i(e, %22
-File not found
+Unable to deserialize
  for key: %22 

Handle serialization exceptions and add an instantiate strategy for no-arg constructor classes.