package com.smaato.sdk.demoapp.banner;

import android.support.annotation.NonNull;

import com.smaato.sdk.banner.ad.BannerAdSize;
import com.smaato.sdk.demoapp.utils.SharedPrefsStorage;

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

import java.util.HashMap;

class BannerAdConfigSerializerDeserializer implements SharedPrefsStorage.SerializerDeserializer<BannerAdConfig> {

    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";
    private static final String KEY_BANNER_AD_SIZE = "banner_ad_size";

    @Override
    @NonNull
    public JSONObject serialize(@NonNull BannerAdConfig 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);
        map.put(KEY_BANNER_AD_SIZE, model.bannerAdSize.ordinal());
        return new JSONObject(map);
    }

    @Override
    @NonNull
    public BannerAdConfig deserialize(@NonNull JSONObject json) {
        String name;
        String publisherId;
        String adSpaceId;
        int bannerAdSizeOrdinal;

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

        return new BannerAdConfig(name, publisherId, adSpaceId, BannerAdSize.values()[bannerAdSizeOrdinal]);
    }
}
