package com.smaato.sdk.demoapp.utils;

import android.content.SharedPreferences;
import android.support.annotation.NonNull;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SharedPrefsStorage<T> {

    @NonNull
    private final SharedPreferences preferences;
    @NonNull
    private final String dataKey;
    @NonNull
    private final SerializerDeserializer<T> serializerDeserializer;

    public SharedPrefsStorage(@NonNull SharedPreferences preferences,
                              @NonNull String dataKey,
                              @NonNull SerializerDeserializer<T> serializerDeserializer) {
        this.preferences = preferences;
        this.serializerDeserializer = serializerDeserializer;
        this.dataKey = dataKey;
    }

    public void put(@NonNull List<T> models) {
        JSONArray array = new JSONArray();
        for (int i = 0, len = models.size(); i < len; ++i) {
            T model = models.get(i);
            JSONObject serialize = serializerDeserializer.serialize(model);
            array.put(serialize);
        }
        String data = array.toString();
        preferences.edit().putString(dataKey, data).commit();
    }

    @NonNull
    public List<T> get() {
        String data = preferences.getString(dataKey, null);
        if (data == null) {
            return new ArrayList<>();
        }

        ArrayList<T> result;
        try {
            JSONArray array = new JSONArray(data);
            result = new ArrayList<>(array.length());
            for (int i = 0, len = array.length(); i < len; ++i) {
                JSONObject json = array.getJSONObject(i);
                T model = serializerDeserializer.deserialize(json);
                result.add(model);
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public interface SerializerDeserializer<T> {

        JSONObject serialize(T model);

        T deserialize(JSONObject json);
    }
}
