package com.iqi.responsys;

import android.content.Intent;
//import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.util.Log;

import com.facebook.react.bridge.WritableNativeMap;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.pushio.manager.PushIOManager;

public class MyResponsysMessagingService extends FirebaseMessagingService {
    private static final String TAG = "RNFMessagingService";

    public static final String MESSAGE_EVENT = "messaging-message";
    public static final String NEW_TOKEN_EVENT = "messaging-token-refresh";
    public static final String REMOTE_NOTIFICATION_EVENT = "notifications-remote-notification";
    @Override
    public void onNewToken(String s) {
        Log.d(TAG, "onNewToken event received");
        super.onNewToken(s);
        // Set the device token in Responsys Mobile SDK
        PushIOManager.getInstance(getApplicationContext()).setDeviceToken(s);
        Intent newTokenEvent = new Intent(NEW_TOKEN_EVENT);
//        LocalBroadcastManager.getInstance(this).sendBroadcast(newTokenEvent);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "onMessageReceived event received");
        super.onMessageReceived(remoteMessage);
        PushIOManager pushIOManager = PushIOManager.getInstance(getApplicationContext());
        Intent notificationEvent = new Intent(MESSAGE_EVENT);
        notificationEvent.putExtra("notification", remoteMessage);
        Log.d(TAG, "remoteMessage : "+remoteMessage);
        WritableNativeMap params = MessagingSerializer.parseRemoteMessage(remoteMessage);

        if (pushIOManager.isResponsysPush(remoteMessage)) {
            if(ResponsysModule.handleMessage) {
                pushIOManager.handleMessage(remoteMessage);
                notificationEvent.putExtra("type", "responsys");
                params.putString("type", "responsys");
                ResponsysModule.sendEvent("messaging_message_received", params);
            }else{
                notificationEvent.putExtra("type", "responsys");
                params.putString("type", "responsys");
                ResponsysModule.sendEvent("messaging_message_received", params);
            }
        } else {
            // Not a Responsys push notification, handle it appropriately
            notificationEvent.putExtra("type", remoteMessage.getMessageType());
            params.putString("type", "others");
            ResponsysModule.sendEvent("messaging_message_received", params);
        }
    }
}
