package xyz.r0r5chach.dermy_app

import android.graphics.BitmapFactory
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.commit
import androidx.recyclerview.widget.RecyclerView
import xyz.r0r5chach.dermy_app.db.DermyDatabase
import xyz.r0r5chach.dermy_app.db.Entities
import xyz.r0r5chach.dermy_app.fragments.MoleFragment
import java.io.File

class MolesAdapter(private val dataSet: List<Entities.Entity?>?, private val filesDir: File): RecyclerView.Adapter<MolesAdapter.ViewHolder>() {
    class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
        val imageView: ImageView = view.findViewById(R.id.mole_list_image)
    }

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

    override fun getItemCount() = dataSet!!.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val mole = (dataSet!![position]!! as Entities.Mole)
        val db = DermyDatabase(holder.imageView.context)

        holder.imageView.setOnClickListener {
            (holder.imageView.context as AppCompatActivity).supportFragmentManager.commit {
                setReorderingAllowed(true)
                replace(R.id.fragment_container, MoleFragment(mole, PredictionMode.NONE, db), null)
                addToBackStack(null)
            }
        }


        holder.imageView.setImageBitmap(BitmapFactory.decodeFile(
            File(filesDir, "${mole.id}.jpg").absolutePath
        ))
    }

}
