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 android.util.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)
                    }
                }
            }
        }
    }

    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
                    }
                    Log.e(TAG, "----handleConversation----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.e(TAG, "----handleMessage----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 findConversationWithPhoneNumber(context: Context, phoneNumber: String, threadId: Long, confirmCallBack: () -> Unit) {
        val hasPerMissionResult = context.hasPermission(PERMISSION_READ_CALL_LOG)
        if (hasPerMissionResult) {
            RecentsHelper(context = context).getRecentCalls(false, Int.MAX_VALUE) { recents: List<RecentCall> ->

                val listCallRecent = recents.distinctBy { it.phoneNumber }
                Log.e(TAG, "----SmsReceiver----最近通话 recents:${listCallRecent}  disListSize:${listCallRecent.size}")
                val findResult: Int = listCallRecent.count { it.phoneNumber.trim() == phoneNumber.trim() }
                //从最近通话记录中找到了号码 进行掩码操作
                if (findResult > 0) {
                    //获取所有短信
                    val allConversations = context.conversationsDB.getNonArchived() as ArrayList<Conversation>
                    Log.e(TAG, " 获取DB 短信列表  allConversations:${GsonUtil.parseListToJson(allConversations)}")

                    val searchResult = getIndexById(allConversations, threadId)
                    Log.e(TAG, "----SmsReceiver----手机号掩码操作 searchResult:${searchResult}")
                    if (searchResult < 0) return@getRecentCalls
                    allConversations.forEach {
                        if (it.threadId == threadId && it.phoneNumber == phoneNumber) {
                            PhoneUtils.phoneNumberFormat(phoneNumber) { itNumber ->
                                Log.e(
                                    TAG,
                                    "----SmsReceiver----手机号掩码操作 itNumber:${itNumber} 所在集合下标=${searchResult} threadId:${it.threadId}  threadId:$threadId  context.getThreadId:${
                                        context.getThreadId(phoneNumber)
                                    }"
                                )
                                val messgeData = allConversations[searchResult].copy(isSFNumber = true, phoneNumber = itNumber)
                                context.conversationsDB.insertOrUpdate(messgeData)

                                context.insertOrUpdateConversation2(messgeData)
                                lastNumber = itNumber
                            }

                        }
                    }
                }
            }
        }
        confirmCallBack.invoke()
    }


    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
    }

}


