package kr.co.compcareworker.Util.Firebase;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.NotificationCompat;

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

import java.util.Map;

import kr.co.compcareworker.Activity.MainActivity;
import kr.co.compcareworker.Activity.PopupActivity;
import kr.co.compcareworker.Fragment.Machine.Alarm_List_Fragment;
import kr.co.compcareworker.MyApplication;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.Util.Service.AlarmThread;


public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    Intent intent = null;
    public static MainActivity activity;
    public static Alarm_List_Fragment alarmListFragment;

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Common.getInstance().setPref(getApplicationContext(), "token", s);
        Log.d("새로운 토큰@@@", s);
        sendRegistrationToServer(s);
    }

    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }

    // 메시지 수신
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Map<String, String> data = remoteMessage.getData();
        for (String key : data.keySet()) {
            Log.d(TAG, key + "(" + data.get(key) + ")");
        }

        String title = data.get("title");
        String send_type = data.get("send_type");
        String message = data.get("body");

        if (!TextUtils.isEmpty(send_type) && send_type.contains("work_write")) {
            if (!Common.getInstance().getPref(getApplicationContext(), "noti_x", true)) {

                intent = new Intent(this, PopupActivity.class)
                        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                if (MyApplication.isBackground) {
                    intent.putExtra("type", "background");
                    intent.putExtra("isMain", false);

                } else {
                    intent.putExtra("isMain", activity != null || alarmListFragment != null);
                    intent.putExtra("type", "foreground");
                }

                intent.putExtra("message", message);
                startActivity(intent);
                sendNotification(title, message, send_type);
            }
        }

        if (!TextUtils.isEmpty(message) && (message.contains("주의") || message.contains("서비스"))) {
            if (Common.getInstance().getPref(getApplicationContext(), "alarm_noti", true)) {

                if (activity != null) {
                    activity.refresh();

                } else if (alarmListFragment != null) {
                    alarmListFragment.refresh();
                }

                if (MyApplication.alarm_thread != null) {
                    MyApplication.alarm_thread.stopForever();
                    MyApplication.alarm_thread = null;
                }

                MyApplication.alarm_thread = new AlarmThread(getApplicationContext(), title, message);
                MyApplication.alarm_thread.start();
            }
        }
    }

    private void sendNotification(String title, String message, String send_type) {
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder;
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel mChannel = new NotificationChannel("andokdcapp", "andokdcapp", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(mChannel);
            notificationBuilder = new NotificationCompat.Builder(this, mChannel.getId());
        } else {
            notificationBuilder = new NotificationCompat.Builder(this);
        }
        notificationBuilder
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.launcher))
                .setSmallIcon(R.mipmap.launcher)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setVibrate(new long[]{0, 3000});

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

    }
}