package com.aiosman.riderpro

import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.aiosman.riderpro.entity.ChatItem
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMMessage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class TrtcService : Service() {
    private var trtcMessageListener: V2TIMAdvancedMsgListener? = null
    private val channelId = "chat_notification"
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("TrtcService", "onStartCommand")
        createNotificationChannel()
        CoroutineScope(Dispatchers.IO).launch {
            registerMessageListener(applicationContext)
        }
        return START_STICKY;
    }


    override fun onDestroy() {
        super.onDestroy()
        Log.d("TrtcService", "onDestroy")
        CoroutineScope(Dispatchers.IO).launch {
            unRegisterMessageListener()
        }
    }

    private fun registerMessageListener(context: Context) {
        val scope = CoroutineScope(Dispatchers.IO)
        trtcMessageListener = object : V2TIMAdvancedMsgListener() {
            override fun onRecvNewMessage(msg: V2TIMMessage?) {
                super.onRecvNewMessage(msg)
                msg?.let {
                    if (MainActivityLifecycle.isForeground) {
                        return
                    }
                    scope.launch {
                        // 先获取通知策略
                        val notiStrategy = ChatState.getStrategyByTargetTrtcId(it.sender)
                        if (notiStrategy == null) {
                            // 未设置策略, 默认通知
                            sendNotification(context, it)
                            return@launch
                        }
                        if (notiStrategy.strategy != "mute") {
                            sendNotification(context, it)
                        }
                    }

                }
            }
        }
        V2TIMManager.getMessageManager().addAdvancedMsgListener(trtcMessageListener)
    }

    private fun unRegisterMessageListener() {
        V2TIMManager.getMessageManager().removeAdvancedMsgListener(trtcMessageListener)
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "Chat Notification"
            val descriptionText = "Notification for chat message"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(channelId, name, importance).apply {
                description = descriptionText
            }
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    private fun sendNotification(context: Context, message: V2TIMMessage) {
        val intent = Intent(context, MainActivity::class.java).apply {
            putExtra("ACTION", "TRTC_NEW_MESSAGE")
            putExtra("SENDER", message.sender)
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }

        val pendingIntent: PendingIntent = PendingIntent.getActivity(
            context,
            0,
            intent,
            PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        val chatItem = ChatItem.convertToChatItem(message, context) ?: return
        val builder = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.mipmap.rider_pro_log_round)
            .setContentTitle(chatItem.nickname)
            .setContentText(chatItem.textDisplay)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)

        with(NotificationManagerCompat.from(context)) {
            if (ActivityCompat.checkSelfPermission(
                    context,
                    Manifest.permission.POST_NOTIFICATIONS
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }
            notify(message.msgID.hashCode(), builder.build())
        }
    }
}