package com.smaato.sdk.demoapp;

import android.app.Application;
import android.content.SharedPreferences;

import com.mopub.common.MoPub;
import com.mopub.common.SdkConfiguration;
import com.mopub.common.logging.MoPubLog;
import com.smaato.sdk.core.Gender;
import com.smaato.sdk.core.SmaatoSdk;
import com.smaato.sdk.demoapp.utils.PreferencesUtils;

import static com.smaato.sdk.demoapp.utils.PreferencesUtils.KEY_AGE;
import static com.smaato.sdk.demoapp.utils.PreferencesUtils.KEY_GENDER;
import static com.smaato.sdk.demoapp.utils.PreferencesUtils.KEY_KEYWORDS;

public class App extends Application {

    private SharedPreferences preferences;

    @Override
    public void onCreate() {
        super.onCreate();
        preferences = PreferencesUtils.getPrefs(this);

        SmaatoSdk.init(this);
        initSdkWithUserSettings();
        initMoPubSDK();
    }

    private void initSdkWithUserSettings() {
        // keywords
        SmaatoSdk.setKeywords(preferences.getString(KEY_KEYWORDS, null));

        // age
        Integer age = null;
        try {
            age = Integer.valueOf(preferences.getString(KEY_AGE, null));
        } catch (NumberFormatException ignored) {
        }
        SmaatoSdk.setAge(age);

        // gender
        Gender gender = null;
        try {
            gender = Gender.values()[preferences.getInt(KEY_GENDER, -1)];
        } catch (ArrayIndexOutOfBoundsException ignored) {
        }
        SmaatoSdk.setGender(gender);
    }

    private void initMoPubSDK() {
        SdkConfiguration sdkConfiguration = new SdkConfiguration.Builder("befde797ef9f4792a8d29c328737f925")
                .withLogLevel(MoPubLog.LogLevel.DEBUG)
                .build();
        MoPub.initializeSdk(this, sdkConfiguration, null);
    }
}
