package com.smaato.sdk.demoapp.interstitial;

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

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

import java.util.List;

class InterstitialAdConfigStorage {

    private static final String PREFS_NAME = "interstitial_ad_config_storage";
    private static final String DATA_KEY = "data";

    @NonNull
    private final SharedPrefsStorage<AdConfig> storage;

    InterstitialAdConfigStorage(@NonNull Context context) {
        SharedPreferences preferences = context.getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        storage = new SharedPrefsStorage<>(preferences, DATA_KEY, new InterstitialAdConfigSerializerDeserializer());
    }

    void updateItem(@NonNull AdConfig oldConfig, AdConfig newConfig) {
        List<AdConfig> configs = get();
        configs.set(configs.indexOf(oldConfig), newConfig);
        storage.put(configs);
    }

    void remove(@NonNull AdConfig adConfig) {
        List<AdConfig> configs = get();
        configs.remove(adConfig);
        storage.put(configs);
    }

    void add(@NonNull AdConfig adConfig) {
        List<AdConfig> configs = get();
        configs.add(adConfig);
        storage.put(configs);
    }

    @NonNull
    List<AdConfig> get() {
        return storage.get();
    }
}
