package net.pokeranalytics.android.ui.adapter.components

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatTextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.view.RowViewType

interface LiveDataDataSource {
    val title: String
    val primaryKey: String
}

interface LiveDataDelegate {
    fun data(position: Int) : LiveDataDataSource
    fun onRowSelected(position: Int)
    fun size() : Int
}

class LiveDataAdapter(var adapterDelegate: LiveDataDelegate, var layout: Int? = null) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    inner class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(row: LiveDataDataSource, listener: View.OnClickListener) {
	        try {
		        itemView.findViewById<AppCompatTextView>(R.id.title).text = row.title
		        itemView.findViewById<ConstraintLayout>(R.id.container).setOnClickListener(listener)
	        } catch (e: Exception) {
		        e.printStackTrace()
	        }

        }
    }

    override fun getItemViewType(position: Int): Int {
        return RowViewType.TITLE.ordinal
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
	    val layoutToInflate = layout ?: R.layout.row_title
        return DataViewHolder(LayoutInflater.from(parent.context).inflate(layoutToInflate, parent, false))
    }

    override fun getItemCount(): Int {
        return adapterDelegate.size()
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
	    val listener = View.OnClickListener {
		    adapterDelegate.onRowSelected(position)
	    }
        (holder as DataViewHolder).bind(this.adapterDelegate.data(position), listener)
    }
}