package com.cpm.lorealbaMabeline.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.DealarBoardActivity;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.dailyactivity.NotificationDetailActivity;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.notification.NotificationUtils;
import static android.app.Notification.DEFAULT_VIBRATE;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final int DEFAULT_SOUND = 1;
    String TAG = "FCM";
    public static  int  NOTIFICATION_ID = 1;
    String body="",path="",title="",type,counter_id="";
    private SharedPreferences preferences;
    String  visit_date;
    long value;
    public MyFirebaseMessagingService() {

    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        preferences = PrefHelper.getPrefs(this);
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");

        body  = remoteMessage.getData().get("body");
        title = remoteMessage.getData().get("title");
        path  = remoteMessage.getData().get("path");
        type  = remoteMessage.getData().get("Mediatype");
        if (!remoteMessage.getData().isEmpty()) {
            //test(TAG, "Message data " + remoteMessage.getData());
            Lorealba_Database db = new Lorealba_Database(this);
            db.open();
            value = db.insertNotificationData(title,body,path,visit_date,type,counter_id);
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            showNotification(body, this, title, path, type, value);
        }
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    @Override
    public void onNewToken(@NonNull String token) {
        //test(TAG, "Refreshed token: " + token);
        sendRegistrationToServer(token);
    }

    private void sendRegistrationToServer(String token) {
    }

    private void showNotification(String body, Context ctx, String title, String path, String type, long value) {
        Intent intent = new Intent(this, NotificationDetailActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(CommonString.KEY_BODY,body);
        intent.putExtra("Path",path);
        intent.putExtra(CommonString.KEY_TITLE,title);
        intent.putExtra("type",type);
        intent.putExtra("KEY_ID",value+"");

        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);

        if (Build.VERSION.SDK_INT >= 26) {
            NotificationUtils mNotificationUtils = new NotificationUtils(this, pendingIntent);
            Notification.Builder nb = mNotificationUtils.
                    getAndroidChannelNotification(title, body);
            mNotificationUtils.getManager().notify(101, nb.build());
        }
        else {
            Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "2")
                    .setSmallIcon(R.mipmap.image)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setAutoCancel(true)
                    .setSound(sound)
                    .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE)
                    .setContentIntent(pendingIntent)
                    .setVibrate(new long[]{0, 500})
                    .setPriority(NotificationManager.IMPORTANCE_HIGH);

            if(NOTIFICATION_ID > 1787258476){
                NOTIFICATION_ID = 0;
            }

            notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        }

        Intent intent1 = new Intent(DealarBoardActivity.PROGRESS_UPDATE);
        LocalBroadcastManager.getInstance(MyFirebaseMessagingService.this).sendBroadcast(intent1);
    }
}
