package fr.plnech.dunbar.ui

import android.text.format.DateUtils
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import fr.plnech.dunbar.model.Friend
import kotlinx.android.synthetic.main.contact_listitem.view.*

class FriendsViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
    private val name = view.contactName
    private val data = view.contactData
    private val phone = view.contactPhone
    private val callButton = view.contactCall
    private val smsButton = view.contactText
    private val pic = view.pic

    fun bind(friend: Friend, onClickListener: ((View) -> Unit)? = null) {
        name.text = friend.name
        data.text = buildDataString(friend)
        view.tag = friend

        bindPhone(friend)
        bindPic(friend)
        bindClick(friend, onClickListener)
    }

    private fun bindPhone(friend: Friend) {
        friend.phone?.let {
            phone.text = it

            mapOf(
                callButton to friend.callIntent(),
                smsButton to friend.smsIntent()
            ).entries.forEach { pair ->
                pair.key.apply {
                    visibility = View.VISIBLE
                    setOnClickListener {
                        view.context.startActivity(pair.value)
                    }
                }
            }
        }
    }

    private fun bindPic(friend: Friend) {
        pic.setImageBitmap(friend.photo)
    }

    private fun bindClick(friend: Friend, onClickListener: ((View) -> Unit)? = null) {
        view.setOnClickListener(onClickListener ?: {
            Toast.makeText(
                view.context,
                friend.mapString(),
                Toast.LENGTH_LONG
            ).show()
            println(friend.mapString())
        })
    }

    private fun buildDataString(friend: Friend): String {
        return buildString {
            if (friend.lastDate != null) {
                append(friend.timesContacted)
                append(" interactions, last ")
                append(DateUtils.getRelativeTimeSpanString(friend.lastTimeStamp))
            } else {
                append("Never interacted")
            }
        }
    }
}