package com.getbubblenow.android.repository;

import android.content.Context;
import android.util.Log;

import com.getbubblenow.android.api.enums.LocalizationDataType;
import com.getbubblenow.android.util.UserStore;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.util.Locale;
import java.util.Map;

import androidx.lifecycle.MutableLiveData;
import io.reactivex.Completable;

/*package*/ class MessageLocalLoader {

    private static final String TAG = "MessageLocalLoader";

    /*package*/ MutableLiveData<Map<String, String>> updatePreAuth(final Context context, final Locale locale) {
        return update(UserStore.getInstance(context).getLocalizationPre());
    }

    /*package*/ MutableLiveData<Map<String, String>> updatePostAuth(final Context context, final Locale locale) {
        return update(UserStore.getInstance(context).getLocalizationPost());
    }

    private MutableLiveData<Map<String, String>> update(final String data) {
        final MutableLiveData<Map<String, String>> mutableLiveData = new MutableLiveData<>();
        final Gson gson = new Gson();
        try {
            final Map<String, String> map = gson.fromJson(data, Map.class);
            mutableLiveData.postValue(map);
        } catch (final JsonSyntaxException ex) {
            Log.e(TAG, "Failed to deserialize localization data from the local storage. " + ex.getMessage(), ex);
            mutableLiveData.postValue(null);
        }
        return mutableLiveData;
    }


    /*package*/ Completable savePreAuth(final Map<String, String> map, final Context context, final Locale locale) {
        return Completable.fromRunnable(() -> saveToSharedPrefs(map, context, locale, LocalizationDataType.PRE_AUTH));
    }

    /*package*/ Completable savePostAuth(final Map<String, String> map, final Context context, final Locale locale) {
        return Completable.fromRunnable(() -> saveToSharedPrefs(map, context, locale, LocalizationDataType.POST_AUTH));
    }

    private void saveToSharedPrefs(
            final Map<String, String> map,
            final Context context,
            final Locale locale,
            final LocalizationDataType localizationDataType) {
        final Gson gson = new Gson();
        final String data =  gson.toJson(map);

        switch (localizationDataType) {
            case PRE_AUTH:
                UserStore.getInstance(context).setLocalizationPre(data);
                break;
            case POST_AUTH:
                UserStore.getInstance(context).setLocalizationPost(data);
                break;
            default:
                throw new IllegalStateException("Message localization data type is not defined.");
        }
    }
}
