package fr.plnech.dunbar.model

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.provider.ContactsContract.Contacts
import java.util.*

data class Friend(val map: Map<String, String?> = mutableMapOf(), val photo: Bitmap? = null) {
    override fun toString(): String = "$name"

    fun mapString(): String = map.entries.filter { !it.value.isNullOrEmpty() }.toString()

    val name: String?
        get() = map[Contacts.DISPLAY_NAME]

    val firstName: String?
        get() = name?.split(Regex("\\s"))?.firstOrNull()

    val id: Int
        get() = (map[Contacts._ID] ?: error("No id for friend $name")).toInt()

    val phone: String?
        get() = if (map[Contacts.HAS_PHONE_NUMBER] == "1") map["data1"] else null

    val lastTimeStamp = map[Contacts.LAST_TIME_CONTACTED]?.toLong() ?: 0

    val lastDate: Date?
        get() = if (lastTimeStamp > 0) Date(lastTimeStamp) else null

    //FIXME: Broken on AndroidQ. Use messages / phone log
    val timesContacted: Int
        get() = map[Contacts.TIMES_CONTACTED]?.toInt() ?: 0

    val isYou: String?
        get() = map[Contacts.IS_USER_PROFILE]

    val visibleOutsideSearch: String?
        get() = map[Contacts.IN_DEFAULT_DIRECTORY]

    fun smsIntent(): Intent? {
        return phone?.let {
            val uri = Uri.parse("smsto:${it}")
            Intent(Intent.ACTION_SENDTO, uri).apply {
                putExtra("sms_body", "Hey ${firstName}, how are you?")
            }
        }
    }

    fun callIntent(): Intent? {
        return phone?.let {
            Intent(Intent.ACTION_DIAL, Uri.parse("tel:${it}"))
        }
    }
}

