package fr.plnech.dunbar.ui

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


class FriendsAdapter(
    private var friends: List<Friend> = mutableListOf()
) : RecyclerView.Adapter<FriendsViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendsViewHolder =
        FriendsViewHolder(
            LayoutInflater.from(parent.context).inflate(viewType, parent, false)
        )

    override fun getItemCount(): Int = friends.size

    override fun getItemViewType(position: Int): Int = R.layout.contact

    override fun onBindViewHolder(holder: FriendsViewHolder, position: Int): Unit =
        holder.bind(friends[position])
}

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) {
        name.text = friend.name
        data.text = buildDataString(friend)

        bindPhone(friend)
        bindPic(friend)
        bindClick(friend)
    }

    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) {
        view.setOnClickListener {
            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")
            }
        }
    }

}
