package fr.plnech.dunbar.data

import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import android.provider.Telephony


class Messages(context: Context) {

    private val contentResolver = context.contentResolver
    var inbox: MutableList<Map<String, String?>> = mutableListOf()
    var sent: MutableList<Map<String, String?>> = mutableListOf()

    fun fetchAll() {
        inbox = fetchMessages(Telephony.Sms.Inbox.CONTENT_URI)
        sent = fetchMessages(Telephony.Sms.Sent.CONTENT_URI)
    }

    @SuppressLint("Recycle") // Cursor is recycled when nonnull
    private fun fetchMessages(uri: Uri): MutableList<Map<String, String?>> {
        val messages = mutableListOf<Map<String, String?>>()

        contentResolver.query(uri, null, null, null, null).let {
            if (it != null) {
                if (it.moveToFirst()) {
                    while (it.moveToNext()) {

                        println("Processing message.")
                        val msg = mutableMapOf<String, String?>()
                        for (i in 0 until it.count) {
                            for (col in it.columnNames) {
                                val index = it.getColumnIndex(col)
                                msg[col] = it.getString(index)
                            }
                        }
                        messages.add(msg)
                    }
                } else {
                    println("No messages in ${uri.toString().replace("content://sms/", "")}.")
                }
                it.close()
            } else {
                println("Null cursor.")
            }
        }
        return messages
    }
}