package com.secspace.sms.receivers

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.provider.Telephony
import com.secspace.log.Log
import com.secspace.sms.extensions.*
import com.secspace.sms.helpers.RecentsHelper
import com.secspace.sms.helpers.refreshMessages
import com.secspace.sms.models.Conversation
import com.secspace.sms.models.Message
import com.secspace.sms.models.RecentCall
import com.secspace.sms.util.PhoneUtils
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.getMyContactsCursor
import com.simplemobiletools.commons.extensions.hasPermission
import com.simplemobiletools.commons.extensions.isNumberBlocked
import com.simplemobiletools.commons.helpers.PERMISSION_READ_CALL_LOG
import com.simplemobiletools.commons.helpers.SimpleContactsHelper
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.commons.models.PhoneNumber
import com.simplemobiletools.commons.models.SimpleContact
import com.simplemobiletools.commons.util.GsonUtil

class SmsReceiver : BroadcastReceiver() {
    private val TAG: String = "shuju"

    //    private var findPhoneNumber = false
    private var lastNumber = ""

    override fun onReceive(context: Context, intent: Intent) {

        val messages = Telephony.Sms.Intents.getMessagesFromIntent(intent)
        var address = ""
        var body = ""
        var subject = ""
        var date = 0L
        var threadId = 0L
        var status = Telephony.Sms.STATUS_NONE
        val type = Telephony.Sms.MESSAGE_TYPE_INBOX
        val read = 0
        val subscriptionId = intent.getIntExtra("subscription", -1)

        val privateCursor = context.getMyContactsCursor(favoritesOnly = false, withPhoneNumbersOnly = true)
        ensureBackgroundThread {
            messages.forEach {
                address = it.originatingAddress ?: ""
                subject = it.pseudoSubject
                status = it.status
                body += it.messageBody
                date = System.currentTimeMillis()
                threadId = context.getThreadId(address)
            }

            if (address.isNotEmpty()) {
                findConversationWithPhoneNumber(context, address, threadId) {
                    if (context.baseConfig.blockUnknownNumbers) {
                        val simpleContactsHelper = SimpleContactsHelper(context)
                        simpleContactsHelper.exists(address, privateCursor) { exists ->
                            if (exists) {
                                handleMessage(context, address, subject, body, date, read, threadId, type, subscriptionId, status)
                            }
                        }
                    } else {
                        handleMessage(context, address, subject, body, date, read, threadId, type, subscriptionId, status)
                    }
                }
            }
        }
    }


    /**
     * 1.先从短信DB库查找
     * 2.未找到再从 通话记录中查找
     */
    private fun findConversationWithPhoneNumber(context: Context, phoneNumber: String, threadId: Long, confirmCallBack: () -> Unit) {

        Log.d(TAG, "----SmsReceiver---- phoneNumber:${phoneNumber}  threadId:$threadId")
        val hasPerMissionResult = context.hasPermission(PERMISSION_READ_CALL_LOG)
        if (hasPerMissionResult) {

            val allConversations = context.conversationsDB.getNonArchived() as ArrayList<Conversation>
//            Log.d(TAG, "----SmsReceiver----handleMessage allConversations:${GsonUtil.parseListToJson(allConversations)}")

            allConversations.forEach {
                if (it.title.trim() == phoneNumber && it.isSFNumber) {
                    lastNumber = it.phoneNumber
                    Log.d(TAG, "----SmsReceiver--conversationsDB数据库--lastNumber :$lastNumber")
                    return@forEach
                }
            }

            if (lastNumber.isEmpty()) {
                RecentsHelper(context = context).getRecentCalls(false, Int.MAX_VALUE) { recents: List<RecentCall> ->
                    val listCallRecent: List<RecentCall> = recents.distinctBy { it.phoneNumber }
//                Log.d(TAG, "----SmsReceiver----最近通话 recents:${GsonUtil.parseListToJson(listCallRecent)}")
                    val findResult: Int = listCallRecent.count { it.phoneNumber.trim() == phoneNumber.trim() && it.isShunFeng }
                    Log.d(TAG, "----SmsReceiver----findResult:${findResult}")
                    //从最近通话记录中找到了号码 进行掩码操作
                    if (findResult > 0) {
                        PhoneUtils.phoneNumberFormat(phoneNumber) { itNumber ->
                           /* Log.d(
                                TAG,
                                "----SmsReceiver----手机号掩码操作 itNumber:${itNumber}  threadId:$threadId  context.getThreadId:${
                                    context.getThreadId(
                                        phoneNumber
                                    )
                                }"
                            )*/
                            lastNumber = itNumber
                        }
                    }
                }
            }
        }
        confirmCallBack.invoke()
    }


    private fun handleMessage(
        context: Context,
        address: String,
        subject: String,
        body: String,
        date: Long,
        read: Int,
        threadId: Long,
        type: Int,
        subscriptionId: Int,
        status: Int
    ) {
        if (isMessageFilteredOut(context, body)) {
            return
        }

        val photoUri = SimpleContactsHelper(context).getPhotoUriFromPhoneNumber(address)
        val bitmap = context.getNotificationBitmap(photoUri)
        Handler(Looper.getMainLooper()).post {
            if (!context.isNumberBlocked(address)) {
                val privateCursor = context.getMyContactsCursor(favoritesOnly = false, withPhoneNumbersOnly = true)
                ensureBackgroundThread {
                    val newMessageId: Long = context.insertNewSMS(address, subject, body, date, read, threadId, type, subscriptionId)

                    val conversation: Conversation = context.getConversations(threadId).firstOrNull() ?: return@ensureBackgroundThread

                    if (lastNumber.isNotBlank()) {
                        conversation.phoneNumber = lastNumber
                        conversation.isSFNumber = true
                    }
//                    Log.d(TAG, "----SmsReceiver----handleConversation 掩码后的 Json:${GsonUtil.parseBeanToJson(conversation)}")
                    try {
                        context.insertOrUpdateConversation(conversation)
                    } catch (ignored: Exception) {
                    }

                    try {
                        context.updateUnreadCountBadge(context.conversationsDB.getUnreadConversations())
                    } catch (ignored: Exception) {
                    }

                    var senderName = context.getNameFromAddress(address, privateCursor)
                    var phoneNumber = PhoneNumber(address, 0, "", address)

                    if (lastNumber.isNotBlank()) {
                        senderName = context.getNameFromAddress(lastNumber, privateCursor)
                        phoneNumber = PhoneNumber(lastNumber, 0, "", lastNumber)
                    }

                    val participant = SimpleContact(0, 0, senderName, photoUri, arrayListOf(phoneNumber), ArrayList(), ArrayList())
                    val participants = arrayListOf(participant)
                    val messageDate = (date / 1000).toInt()


                    var message =
                        Message(
                            newMessageId,
                            body,
                            type,
                            status,
                            participants,
                            messageDate,
                            false,
                            threadId,
                            false,
                            null,
                            address,
                            senderName,
                            photoUri,
                            subscriptionId
                        )
                    if (lastNumber.isNotBlank()) {
                        message =
                            Message(
                                newMessageId,
                                body,
                                type,
                                status,
                                participants,
                                messageDate,
                                false,
                                threadId,
                                false,
                                null,
                                lastNumber,
                                senderName,
                                photoUri,
                                subscriptionId
                            )
                    }
//                    Log.d(TAG, "----SmsReceiver----handleMessage message:${GsonUtil.parseBeanToJson(message)}")
                    context.messagesDB.insertOrUpdate(message)
                    if (context.config.isArchiveAvailable) {
                        context.updateConversationArchivedStatus(threadId, false)
                    }
                    refreshMessages()
                    if (lastNumber.isNotBlank()) {
                        context.showReceivedMessageNotification(newMessageId, lastNumber, body, threadId, bitmap)
                    } else {
                        context.showReceivedMessageNotification(newMessageId, address, body, threadId, bitmap)
                    }
                    lastNumber = ""
                }
            }
        }
    }

    private fun isMessageFilteredOut(context: Context, body: String): Boolean {
        for (blockedKeyword in context.config.blockedKeywords) {
            if (body.contains(blockedKeyword, ignoreCase = true)) {
                return true
            }
        }
        return false
    }


    private fun getIndexById(userList: List<Conversation>, id: Long): Int {
        for (i in userList.indices) {
            if (userList[i].threadId === id) {
                return i // 找到匹配的ID，返回下标
            }
        }
        return -1 // 如果未找到，返回-1
    }

}


