package fr.plnech.dunbar

import android.content.ContentUris
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.provider.ContactsContract
import fr.plnech.dunbar.model.Friend
import java.io.IOException

fun String.plural(count: Int = 1): String {
    return when {
        count > 1 -> this + "s"
        else -> this
    }
}

fun Context.fetchContacts(includeNot: Boolean = true): List<Friend> {
    // TODO: https://developer.android.com/training/permissions/requesting
    val friends = mutableListOf<Friend>()

    //TODO: More efficient query using non-null parameters
    contentResolver.query(
        ContactsContract.CommonDataKinds.Contactables.CONTENT_URI,
        null,
        null,
        null,
        null
    )?.let {
        while (it.moveToNext()) {
            mutableMapOf<String, String?>().also { map ->
                val indexId = it.getColumnIndex(ContactsContract.Contacts._ID)
                val id = it.getLong(indexId)
                val photo: Bitmap? = getFriendPhoto(id)

                it.columnNames.forEach { name ->
                    val index = it.getColumnIndex(name)
                    map[name] = it.getString(index)
                }
                friends.add(Friend(map, photo))
            }
        }
        it.close()
    }

    println("Fetched ${friends.size} friends.")

    return (if (includeNot) friends else friends.filter { it.lastDate != null })
        .sortedByDescending { it.timesContacted }
}


private fun Context.getFriendPhoto(id: Long): Bitmap? {
    var photo: Bitmap? = null

    try {
        val inputStream = ContactsContract.Contacts.openContactPhotoInputStream(
            contentResolver,
            ContentUris.withAppendedId(
                ContactsContract.Contacts.CONTENT_URI,
                java.lang.Long.valueOf(id)
            )
        )

        if (inputStream != null) {
            photo = BitmapFactory.decodeStream(inputStream)
        }

        inputStream?.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return photo
}