package kr.co.icontrols.iotplatform.Service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;

import androidx.core.app.NotificationCompat;

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

import kr.co.icontrols.iotplatform.PopupActivity;
import kr.co.icontrols.iotplatform.R;

import static kr.co.icontrols.iotplatform.utils.CommonUtils.DebugLogOutput;
import static kr.co.icontrols.iotplatform.utils.SharedPrefUtil.PUSH_TOKEN;
import static kr.co.icontrols.iotplatform.utils.SharedPrefUtil.putString;

/**
 * Push 서비스 이용을 위한 Service
 */
public class MessagingService extends FirebaseMessagingService {
    private final String TAG = "MessagingService";
    private final String channelId = "HDC_IOT";
    private final String channelName = "HDC_IOT_APP";
    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        DebugLogOutput(TAG, "onNewToken: " + s);
        putString(PUSH_TOKEN,s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        DebugLogOutput(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            DebugLogOutput(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                //scheduleJob();
            } else {
                // Handle message within 10 seconds
                //handleNow();
            }
        }

        if (remoteMessage.getNotification() != null) {
            DebugLogOutput(TAG, "Message Notification Title: " + remoteMessage.getNotification().getTitle());
            DebugLogOutput(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            showNotification(remoteMessage);
        } else if(remoteMessage.getData() != null) {
            DebugLogOutput(TAG, "Message Data Title: " + remoteMessage.getData().get("title"));
            DebugLogOutput(TAG, "Message Data Body: " + remoteMessage.getData().get("body"));
            showData(remoteMessage);
        }

        // 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.
    }

    /**
     * 사용자에게 Push 메시지 표시하는 함수
     * @param remoteMessage
     */
    private void showNotification(RemoteMessage remoteMessage) {

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

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(channelId, channelName, importance);
            notifManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channelId);
        Intent notificationIntent = new Intent(getApplicationContext(), PopupActivity.class);
        notificationIntent.putExtra(PopupActivity.POPUP_MODE,PopupActivity.MODE_NORMAL);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        notificationIntent.putExtra(PopupActivity.POPUP_TITLE_TEXT,remoteMessage.getNotification().getTitle());
        notificationIntent.putExtra(PopupActivity.POPUP_BODY_TEXT,remoteMessage.getNotification().getBody());

        int requestID = (int) System.currentTimeMillis();

        PendingIntent pendingIntent
                = PendingIntent.getActivity(getApplicationContext()
                , requestID
                , notificationIntent
                , PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentTitle(remoteMessage.getNotification().getTitle()) // required
                .setContentText(remoteMessage.getNotification().getBody())  // required
                .setDefaults(Notification.DEFAULT_ALL) // 알림, 사운드 진동 설정
                .setAutoCancel(true) // 알림 터치시 반응 후 삭제
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setSmallIcon(R.drawable.app_icon_png_02)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                //.setBadgeIconType(R.drawable.msg_icon)
                .setContentIntent(pendingIntent);

        notifManager.notify(0, builder.build());
    }

    /**
     * 사용자에게 Push 메시지 표시하는 함수
     * @param remoteMessage
     */
    private void showData(RemoteMessage remoteMessage) {

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

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(channelId, channelName, importance);
            notifManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channelId);
        Intent notificationIntent = new Intent(getApplicationContext(), PopupActivity.class);
        notificationIntent.putExtra(PopupActivity.POPUP_MODE,PopupActivity.MODE_NORMAL);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        notificationIntent.putExtra(PopupActivity.POPUP_BODY_TEXT, remoteMessage.getData().get("title") + "\n\n" + remoteMessage.getData().get("body"));

        int requestID = (int) System.currentTimeMillis();

        PendingIntent pendingIntent
                = PendingIntent.getActivity(getApplicationContext()
                , requestID
                , notificationIntent
                , PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentTitle(remoteMessage.getData().get("title")) // required
                .setContentText(remoteMessage.getData().get("body"))  // required
                .setDefaults(Notification.DEFAULT_ALL) // 알림, 사운드 진동 설정
                .setAutoCancel(true) // 알림 터치시 반응 후 삭제
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setSmallIcon(R.drawable.app_icon_png_02)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                //.setBadgeIconType(R.drawable.msg_icon)
                .setContentIntent(pendingIntent);

        notifManager.notify(0, builder.build());
    }
}
