package com.steps.tmuapp;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import org.json.JSONException;
import org.json.JSONObject;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    /** The tag for Log.d() */
    private static final String TAG = "=Fcm=";
    public static String FCM_NOTIFICATION_SIGN = "fcm_list";
    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);
        // The instance ID token is registered in FcmRegistration now.
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
//        PreferenceHelper preferenceHelper = new PreferenceHelper(this);
//        if(preferenceHelper.getConfigString(PreferenceHelper.PREFERENCE_Enable_Notification).equals("Y")){
            // Check if message contains a notification payload.
            if (remoteMessage.getNotification() != null) {
                Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
                sendMyNotification(remoteMessage);
//                sendMyNotification(remoteMessage);
            }
            // Check if message contains a data payload.
            if(getResources().getBoolean(R.bool.pushModeData)) {
                if (remoteMessage.getData().size() > 0) {
                    Log.d(TAG, "Message data payload: " + remoteMessage.getData());
                    try {
                        JSONObject json = new JSONObject(remoteMessage.getData().toString());
                        handleDataMessage(json);
                    } catch (Exception e) {
                        Log.e(TAG, "Exception: " + e.getMessage());
                    }
                }
            }
//        }
    }

    private void sendNotification(RemoteMessage remoteMessage) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);

        String channelId = getString(R.string.notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.org_logo)
                        .setContentTitle(remoteMessage.getNotification().getTitle())
                        .setContentText(remoteMessage.getNotification().getBody())
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

    private void sendMyNotification(RemoteMessage remoteMessage) {
        Log.d(TAG, "> sendMyNotification: " );
        //On click of notification it redirect to this Activity

        //String click_action = ToolsHelper.requireNonNull(remoteMessage.getNotification()).getClickAction();

        Intent intent = new Intent(this, MainActivity.class);
//        Intent intent = new Intent("OPEN_NTPU_PUSH_ACTIVITY");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("target", FCM_NOTIFICATION_SIGN);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channelPush = new NotificationChannel(
                    getString(R.string.channelId),
                    getString(R.string.channelName),
                    NotificationManager.IMPORTANCE_HIGH);
            channelPush.setDescription(getString(R.string.channelDescription));
            channelPush.enableLights(true);
            channelPush.enableVibration(true);

            assert notificationManager != null;
            notificationManager.createNotificationChannel(channelPush);
        }

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Using Notification Payload");
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,
                    getString(R.string.channelId))
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(getString(R.string.notification_title))
                    .setContentText(remoteMessage.getNotification().getBody())
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);
            assert notificationManager != null;
            notificationManager.notify(0, notificationBuilder.build());
        }else if (remoteMessage.getData() != null){
            Log.d(TAG, "Using Data Payload");
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,
                    getString(R.string.channelId))
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(getString(R.string.notification_title))
                    .setContentText(remoteMessage.getData().get("body"))
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);
            assert notificationManager != null;
            notificationManager.notify(0, notificationBuilder.build());
        }
        Log.d(TAG, "< sendMyNotification: " );
    }

    private void handleDataMessage(JSONObject json) {

        try {
            JSONObject data = json.getJSONObject("data");

            String title = "TMU APP";
            String message = data.getString("message");
            String click_action = data.getString("click_action");
            // TODO: to be removed: These 3 columns are not used
            //boolean isBackground = data.getBoolean("is_background");
            //String timestamp = data.getString("timestamp");
            //JSONObject payload = data.getJSONObject("payload");

            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            if (Build.VERSION.SDK_INT >= 26) {
                NotificationChannel channelPush = new NotificationChannel(
                        "channelPush",
                        getString(R.string.notification_channel_name),
                        NotificationManager.IMPORTANCE_HIGH);
                channelPush.setDescription(getString(R.string.notification_channel_description));
                channelPush.enableLights(true);
                channelPush.enableVibration(true);

                assert notificationManager != null;
                notificationManager.createNotificationChannel(channelPush);
            }

            Intent intent = new Intent(click_action);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(this,"channelPush")
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(title)
                            .setContentText(message)
                            .setAutoCancel(true)
                            .setContentIntent(pendingIntent);

            assert notificationManager != null;
            notificationManager.notify(0, mBuilder.build());

        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}
