package fr.plnech.dunbar.ui

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import fr.plnech.dunbar.R
import fr.plnech.dunbar.model.Friend

class FriendsPanesViewAdapter(
    private val parentActivity: FriendListActivity,
    private val friends: List<Friend>,
    private val twoPane: Boolean
) :
    RecyclerView.Adapter<FriendsViewHolder>() {

    private val onClickListener: View.OnClickListener

    init {
        onClickListener = View.OnClickListener { v ->
            val friend = v.tag as Friend
            if (twoPane) {
                val fragment = FriendDetailFragment().apply {
                    arguments = Bundle().apply {
                        putInt(FriendDetailFragment.ARG_FRIEND_ID, friend.id)
                    }
                }
                parentActivity.supportFragmentManager
                    .beginTransaction()
                    .replace(R.id.friend_detail_container, fragment)
                    .commit()
            } else {
                val intent = Intent(
                    v.context,
                    FriendDetailActivity::class.java
                ).apply {
                    putExtra(FriendDetailFragment.ARG_FRIEND_ID, friend.id)
                }
                v.context.startActivity(intent)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendsViewHolder {
        return FriendsViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.contact_listitem, parent, false)
        )
    }

    override fun onBindViewHolder(holder: FriendsViewHolder, position: Int) {
        holder.bind(friends[position]) { onClickListener.onClick(it) }
    }

    override fun getItemCount() = friends.size
}