package com.ridocula.restdroid.adapters

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.ridocula.restdroid.R
import com.ridocula.restdroid.models.HistoryRequest
import com.ridocula.restdroid.models.Request

/**
 * [RecyclerView.Adapter] that can display a [Request] and makes a call to the
 * specified [OnListFragmentInteractionListener].
 */
class HistoryRequestRecyclerViewAdapter(values: List<HistoryRequest>, private val mListener: OnItemClickedListener?) : RecyclerView.Adapter<HistoryRequestRecyclerViewAdapter.ViewHolder>() {

    private var mRequests: MutableList<HistoryRequest> = ArrayList()

    init {
        mRequests.addAll(values)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_request, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.mType.text = mRequests[position].type.toString()
        holder.mUrl.text = mRequests[position].url

        holder.mView.setOnClickListener {
            mListener?.onItemClicked(mRequests[position])
        }
    }

    fun addItem(request: HistoryRequest) {
        mRequests.add(request)
        notifyItemInserted(mRequests.size - 1)
    }

    fun setData(data: List<HistoryRequest>) {
        mRequests.clear()
        mRequests.addAll(data)
        notifyDataSetChanged()
    }

    fun clearItems() {
        mRequests.clear()
        notifyDataSetChanged()
    }

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

    inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) {
        val mParentView: LinearLayout
        val mType: TextView
        var mUrl: TextView

        init {
            mParentView = mView.findViewById<LinearLayout>(R.id.llRequest) as LinearLayout
            mType = mView.findViewById<TextView>(R.id.tvType) as TextView
            mUrl = mView.findViewById<TextView>(R.id.tvUrl) as TextView

        }

        override fun toString(): String {
            return super.toString() + " '" + mUrl.text + "'"
        }
    }

    interface OnItemClickedListener {
        fun onItemClicked(item: HistoryRequest)
    }
}
