package com.secspace.sms.receivers

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.core.app.RemoteInput
import com.secspace.sms.extensions.*
import com.secspace.sms.helpers.REPLY
import com.secspace.sms.helpers.THREAD_ID
import com.secspace.sms.helpers.THREAD_NUMBER
import com.secspace.sms.helpers.THREAD_TITLE
import com.secspace.sms.messaging.sendMessageCompat
import com.simplemobiletools.commons.extensions.showErrorToast
import com.simplemobiletools.commons.helpers.SimpleContactsHelper
import com.simplemobiletools.commons.helpers.ensureBackgroundThread

class DirectReplyReceiver : BroadcastReceiver() {
    private val TAG = DirectReplyReceiver::class.java.simpleName

    @SuppressLint("MissingPermission")
    override fun onReceive(context: Context, intent: Intent) {
        //正常/掩码手机号
        val aesPhoneNumber = intent.getStringExtra(THREAD_TITLE) ?: ""
        Log.d(TAG, "onReceive: aesPhoneNumber = $aesPhoneNumber")
        var address = intent.getStringExtra(THREAD_NUMBER) ?: ""
        Log.d(TAG, "onReceive: address = $address")
        val threadId = intent.getLongExtra(THREAD_ID, 0L)
        var body = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(REPLY)?.toString() ?: return

        body = context.removeDiacriticsIfNeeded(body)

        if (address.isNotBlank()) {
            if(address.contains("+86")){
                address = address.replace("+86","")
            }
            var subscriptionId: Int? = null
            val availableSIMs = context.subscriptionManagerCompat().activeSubscriptionInfoList
            if ((availableSIMs?.size ?: 0) > 1) {
                val currentSIMCardIndex = context.config.getUseSIMIdAtNumber(address)
                val wantedId = availableSIMs.getOrNull(currentSIMCardIndex)
                if (wantedId != null) {
                    subscriptionId = wantedId.subscriptionId
                }
            }

            ensureBackgroundThread {
                var messageId = 0L
                try {
                    context.sendMessageCompat(body, listOf(address), subscriptionId, emptyList())
                    val message = context.getMessages(threadId, getImageResolutions = false, includeScheduledMessages = false, limit = 1).lastOrNull()
//                    Log.d(TAG, "onReceive: message = ${Gson().toJson(message)}")
                    if (message != null) {
                        context.messagesDB.insertOrUpdate(message)
                        messageId = message.id
                        Log.d(TAG, "onReceive: messageId = $messageId")
                        val containsResult = aesPhoneNumber.contains("*")
                        Log.d(TAG, "onReceive: 手机号不包含 [*] = $containsResult")
                        if (containsResult) {
                            context.updateLastConversationMessage(threadId, true)
                        } else {
                            context.updateLastConversationMessage(threadId, false)
                        }
                    }
                } catch (e: Exception) {
                    context.showErrorToast(e)
                }

                val photoUri = SimpleContactsHelper(context).getPhotoUriFromPhoneNumber(address)
                val bitmap = context.getNotificationBitmap(photoUri)
                Handler(Looper.getMainLooper()).post {
                    if (aesPhoneNumber.contains("*")) {
                        Log.d(TAG, "handleMessage: 掩码号码")
                        context.notificationHelper.showMessageNotification(messageId, aesPhoneNumber, body, threadId, bitmap, sender = null, alertOnlyOnce = true, normalNumber = address)
                    } else {
                        context.notificationHelper.showMessageNotification(messageId, address, body, threadId, bitmap, sender = null, alertOnlyOnce = true)
                    }
                }

                context.markThreadMessagesRead(threadId)
                context.conversationsDB.markRead(threadId)
            }
        }
    }
}
