package gsort.pos.engsisubiq.EmileMobile;

// import android.util.Log;

import java.util.Map;
import java.util.Random;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.SharedPreferences;
import android.provider.Settings;
import android.provider.Settings.System;
import com.google.firebase.messaging.RemoteMessage;
import com.google.firebase.messaging.FirebaseMessagingService;

import org.json.JSONObject;

/**
 * Please! To read about Firebase Push Notification, take a look in Firebase Documentation Message API
 * https://developers.google.com/android/reference/com/google/firebase/messaging/RemoteMessage
 * The version of Firebase Messaging used is especify in build.gradle file in android folder
 * at: compile 'com.google.firebase:firebase-messaging:9.6.1'
 * The next job is to append messages in single notification like whatsapp:
 * https://stackoverflow.com/questions/33040737/how-to-group-android-notifications-like-whatsapp
 */
public class FirebaseListenerService extends FirebaseMessagingService
{
    private SharedPreferences sharedPreferences;

    /**
     * Called when message is received and app is running (background or foreground).
     *
     * @param from SenderID of the sender.
     * @param data Data bundle containing message data as key/value pairs.
     *             For Set of keys use data.keySet().
     * To receive notification when app is in background or closed, the message send to firebase
     * cannot have the 'notification' key! And all data needs to be in 'data' keywork.
     * To more details, check the follow links:
     * https://stackoverflow.com/questions/42480002/findout-when-firebase-message-recieved-when-app-in-background
     * https://stackoverflow.com/questions/37711082/how-to-handle-notification-when-app-in-background-in-firebase#answer-37845174
     */
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage)
    {
        // initialize the sharedPreferences with application context (required)
        Context c = getApplicationContext();
        sharedPreferences = c.getSharedPreferences(c.getPackageName(), Context.MODE_PRIVATE);

        // https://developers.google.com/android/reference/com/google/firebase/messaging/RemoteMessage.Notification
        RemoteMessage.Notification notification = remoteMessage.getNotification();
        Map<String,String> extraData = remoteMessage.getData();

        // whe app is in background or closed, the notification object
        // is null, because all push data become in remoteMessage.getData()
        if (notification != null) {
            extraData.put("title", notification.getTitle());
            extraData.put("message", notification.getBody());
            // add some extra paramenters that can become in the push message
            // clickAction specify the activity to open when user click in the message
            extraData.put("clickAction", notification.getClickAction());
            // color, set a custom color to the icon
            extraData.put("color", notification.getColor());
            // icon, set a custom icon to message notification.
            // However, the icon needs to be in drawable resources package and
            // the icon needs to be a string with icon file name without the file extension.
            extraData.put("icon", notification.getIcon());
        } else {
            try {
                extraData.put("message", extraData.get("body"));
            } catch(Exception e) {
                // Log.e("FirebaseListenerService", e);
            }
        }

        // show system notification
        sendNotification(extraData, (int) remoteMessage.getSentTime(), remoteMessage.getFrom());
    }

    // android system notification has many options!
    // take a look in documentation for more details in follow links:
    // https://developer.android.com/guide/topics/ui/notifiers/notifications.html
    // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html
    public void sendNotification(Map<String,String> extraData, int messageId, String sender)
    {
        int badgeNum        = sharedPreferences.getInt("badgeNumber", 0);
        JSONObject json     = null;
        String messageData  = null;
        String title        = extraData.get("title");
        String message      = extraData.get("message");

        // this JSONObject is needed to serialize the Map as string
        // to pass to QtApplication as argument when user click in notification
        try {
            json = new JSONObject(extraData);
            messageData = json.toString();
        } catch(Exception e) {
            // Log.e("FirebaseListenerService", e);
        }

        // create a new intent to send to the Activity that will be pass to QtApplication.
        // The push message pay load data will be serialized and sent as argument when user click in the notification
        // the messagaData value can be read as a new Intent extra parameter in onResume(...) method
        // this feature works only if the app is opened!
        Intent intent = new Intent(this, CustomActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("messageData", messageData);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder notificationBuilder = new Notification.Builder(this);
        // play default notification sound (if available)
        notificationBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
        // start vibration if user enable vibration to the app
        notificationBuilder.setVibrate(new long[] {500, 500, 500});
        // start the device LED notification (available only in some devices)
        notificationBuilder.setLights(Color.BLUE, 3000, 3000);

        // create pending intent, a mention to the Activity which needs to be
        // triggered when user clicks in the notification. In this case is QtActivity class
        PendingIntent contentIntent = PendingIntent.getActivity(this, messageId, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setColor(getResources().getColor(R.color.colorPrimary));
        notificationBuilder.setContentIntent(contentIntent);
        notificationBuilder.setContentText(message);
        notificationBuilder.setContentTitle(title);
        notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
        notificationBuilder.setGroup(sender);
        notificationBuilder.setGroupSummary(true);
        notificationBuilder.setSmallIcon(R.drawable.icon_transparent);

        // show a right number with non read messages
        // saved in shared preferences on each new messages
        if (badgeNum > 0)
            notificationBuilder.setNumber(badgeNum);

        try {
            if (json.getString("tag") != null)
                notificationBuilder.setCategory(json.getString("tag"));
            if (json.getString("color") != null)
                notificationBuilder.setColor(Integer.parseInt(json.getString("color")));
            if (json.getString("icon") != null)
               notificationBuilder.setSmallIcon(Integer.parseInt(json.getString("icon")));
        } catch(Exception e) {
            // Log.e("FirebaseListenerService", e);
        }

        Notification.BigTextStyle bigText = new Notification.BigTextStyle();
        bigText.bigText(message);
        bigText.setBigContentTitle(title);

        try {
            message = "";
            message = json.getString("name");
            if (message != null && !message.equals(""))
                bigText.setSummaryText(":: " + message);
        } catch(Exception e) {
            // Log.e("FirebaseListenerService", e);
        }

        notificationBuilder.setStyle(bigText);
        notificationManager.notify(messageId, notificationBuilder.build());

        // send the push notification message to QtApplication
        // if the app is opened (background or foreground)
        if (messageData != null && !messageData.equals("") && CustomActivity.isRunning) {
            try {
                ActivityToApplication.eventNotify("newPushMessage", messageData);
            } catch(Exception e) {
                // Log.e("FirebaseListenerService", e);
            }
        }

        // update the badge number if app is not opened
        setBandgeNumber(badgeNum);
    }

    private void setBandgeNumber(int badgeNum)
    {
        badgeNum = badgeNum + 1;
        SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
        prefsEditor.putInt("badgeNumber", badgeNum);
        prefsEditor.apply();
        try {
            BadgeUtils.setBadge(FirebaseListenerService.this, badgeNum);
        } catch(Exception e) {
            // Log.e("FirebaseListenerService", e);
        }
    }
}
