package com.team.app;

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

import com.onesignal.OSNotificationOpenedResult;
import com.onesignal.OneSignal;

import org.json.JSONObject;

public class MyApplication extends Application {

    private static MyApplication mInstance;

    public MyApplication() {
        mInstance = this;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        OneSignal.initWithContext(this);
        OneSignal.setAppId("f71d462e-6c06-4e65-80ef-c59edddc4fb4");
        OneSignal.unsubscribeWhenNotificationsAreDisabled(true);
        OneSignal.setNotificationOpenedHandler(new NotificationHandler());
    }

    class NotificationHandler implements  OneSignal.OSNotificationOpenedHandler{
        @Override
        public void notificationOpened(OSNotificationOpenedResult result) {
            SharedPreferences sp = getSharedPreferences(getResources().getString(R.string.app_name), Context.MODE_PRIVATE);
            SharedPreferences.Editor prefEditor = sp.edit();
            JSONObject data = result.getNotification().getAdditionalData();
            if (data != null && data.has("message") && data.has("link")){
                prefEditor.putString("message",data.optString("message"));
                prefEditor.putString("link", data.optString("link"));
                prefEditor.apply();
            }
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

}
