package kr.co.vividnext.sodalive.fcm

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.os.Build
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.splash.SplashActivity

class SodaFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        if (SharedPreferenceManager.token.isNotBlank()) {
            when {
                remoteMessage.data.isNotEmpty() -> {
                    sendNotification(remoteMessage.data)
                }
            }
        }
    }

    override fun onNewToken(token: String) {
        SharedPreferenceManager.pushToken = token
    }

    private fun sendNotification(messageData: Map<String, String>) {
        val notificationChannelId = getString(R.string.default_notification_channel_id)
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(
                    notificationChannelId,
                    getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_HIGH
                )
            notificationManager.createNotificationChannel(channel)
        }

        val intent = Intent(this, SplashActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)

        val roomId = messageData["room_id"]
        if (roomId != null) {
            intent.putExtra(Constants.EXTRA_ROOM_ID, roomId.toLong())
        }

        val messageId = messageData["message_id"]
        if (messageId != null) {
            intent.putExtra(Constants.EXTRA_MESSAGE_ID, messageId.toLong())
        }

        val audioContentId = messageData["content_id"]
        if (audioContentId != null) {
            intent.putExtra(Constants.EXTRA_AUDIO_CONTENT_ID, audioContentId.toLong())
        }

        val channelId = messageData["channel_id"]
        if (channelId != null) {
            intent.putExtra(Constants.EXTRA_USER_ID, channelId.toLong())
        }

        val pendingIntent =
            PendingIntent.getActivity(
                this,
                System.currentTimeMillis().toInt(),
                intent,
                PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
            )

        val notificationBuilder = NotificationCompat.Builder(this, notificationChannelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(messageData["title"])
            .setContentText(messageData["message"])
            .setSound(defaultSoundUri)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)

        val bigTextStyle = NotificationCompat.BigTextStyle(notificationBuilder)
        bigTextStyle.bigText(messageData["message"])

        notificationManager.notify(System.currentTimeMillis().toInt(), notificationBuilder.build())
    }
}
