package com.smaato.sdk.demoapp.interstitial;

import android.support.annotation.NonNull;

import com.smaato.sdk.demoapp.AdConfig;
import com.smaato.sdk.demoapp.utils.SharedPrefsStorage;

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

import java.util.HashMap;

class InterstitialAdConfigSerializerDeserializer implements SharedPrefsStorage.SerializerDeserializer<AdConfig> {

    private static final String KEY_NAME = "name";
    private static final String KEY_PUBLISHER_ID = "publisher_id";
    private static final String KEY_AD_SPACE_ID = "ad_space_id";

    @Override
    @NonNull
    public JSONObject serialize(@NonNull AdConfig model) {
        HashMap<String, Object> map = new HashMap<>();
        map.put(KEY_NAME, model.name);
        map.put(KEY_PUBLISHER_ID, model.publisherId);
        map.put(KEY_AD_SPACE_ID, model.adSpaceId);
        return new JSONObject(map);
    }

    @Override
    @NonNull
    public AdConfig deserialize(@NonNull JSONObject json) {
        String name;
        String publisherId;
        String adSpaceId;

        try {
            name = json.getString(KEY_NAME);
            publisherId = json.getString(KEY_PUBLISHER_ID);
            adSpaceId = json.getString(KEY_AD_SPACE_ID);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

        return new AdConfig(name, publisherId, adSpaceId);
    }
}
