package com.nxp.vizncompanionapp.adapters

import android.bluetooth.BluetoothDevice
import android.content.Context
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.nxp.vizncompanionapp.R

class BleListAdapter(context: Context) : RecyclerView.Adapter<BleListAdapter.WordViewHolder>() {

    private var mInflater: LayoutInflater? = null
    private var myClickListener: MyClickListener? = null
    private var mBleList: List<BluetoothDevice>? = null
    var context = context

    init {
        mInflater = LayoutInflater.from(context)
        this.context = context
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): BleListAdapter.WordViewHolder {
        val itemView = mInflater?.inflate(R.layout.rv_blelist_item,parent,false)
        return WordViewHolder(itemView!!)
    }

    override fun getItemCount(): Int {
        return if(mBleList != null){
            mBleList!!.size
        } else{
            0
        }
    }

    override fun onBindViewHolder(holder: BleListAdapter.WordViewHolder?, position: Int) {
        holder?.wordItemView!!.text = mBleList?.get(position)?.name
    }

    inner class WordViewHolder (itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
        override fun onClick(v: View) {
            myClickListener?.onItemClick(adapterPosition, v,mBleList)
        }

        val wordItemView: TextView
        val wordItemRvView: CardView

        init {
            wordItemView = itemView.findViewById(R.id.rvBleItem1)
            wordItemRvView = itemView.findViewById(R.id.llRvBleItem)

            wordItemRvView.setOnClickListener(this)
        }

    }

    internal fun setDevices(devices: List<BluetoothDevice>?) {
        mBleList = devices
        notifyDataSetChanged()
    }

    interface MyClickListener {
        fun onItemClick(position: Int, v: View,mDeviceList: List<BluetoothDevice>?)
    }

    /**
     * RecyclerView item click listener
     *
     * @param myClickListener listener
     */
    fun setOnItemClickListener(myClickListener: MyClickListener) {
        this.myClickListener = myClickListener
    }
}