package com.secspace.sms.receivers

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.secspace.sms.extensions.conversationsDB
import com.secspace.sms.extensions.deleteMessage
import com.secspace.sms.extensions.updateLastConversationMessage
import com.secspace.sms.extensions.updateUnreadCountBadge
import com.secspace.sms.helpers.IS_MMS
import com.secspace.sms.helpers.MESSAGE_ID
import com.secspace.sms.helpers.THREAD_ID
import com.secspace.sms.helpers.refreshMessages
import com.simplemobiletools.commons.extensions.notificationManager
import com.simplemobiletools.commons.helpers.ensureBackgroundThread

class DeleteSmsReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val threadId = intent.getLongExtra(THREAD_ID, 0L)
        val messageId = intent.getLongExtra(MESSAGE_ID, 0L)
        val isMms = intent.getBooleanExtra(IS_MMS, false)
        context.notificationManager.cancel(threadId.hashCode())
        ensureBackgroundThread {
            context.deleteMessage(messageId, isMms)
            context.updateUnreadCountBadge(context.conversationsDB.getUnreadConversations())
            context.updateLastConversationMessage(threadId)
            refreshMessages()
        }
    }
}
