package xyz.r0r5chach.dermy_app.fragments

import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import xyz.r0r5chach.dermy_app.MolesAdapter
import xyz.r0r5chach.dermy_app.R
import xyz.r0r5chach.dermy_app.api.Prediction
import xyz.r0r5chach.dermy_app.db.Tables
import xyz.r0r5chach.dermy_app.db.DermyDatabase
import xyz.r0r5chach.dermy_app.db.Entities
import xyz.r0r5chach.dermy_app.map.locations.Location
import java.time.Instant

class LocationFragment(private val location: Location, val db: DermyDatabase): Fragment(R.layout.fragment_location) {
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val list = view.findViewById<RecyclerView>(R.id.moles_list)
        val emptyList = view.findViewById<TextView>(R.id.location_empty_text)
        val moles = mutableListOf<Entities.Mole>()
        with(db.readableDatabase.query(Tables.MOLES.toString(), null, null, null, null, null, null)) {
            while (moveToNext()) {
                moles.add(
                    Entities.Mole(
                        getString(getColumnIndexOrThrow("id")),
                        getString(getColumnIndexOrThrow("userId")),
                        Instant.parse(getString(getColumnIndexOrThrow("dateCreated"))),
                        Location(getString(getColumnIndexOrThrow("location"))),
                        Prediction(getString(getColumnIndexOrThrow("prediction")))
                    )
                )
            }
            close()
        }
        val adapter = MolesAdapter(moles, requireContext().filesDir)
        list.layoutManager = GridLayoutManager(context, 3)
        list.adapter = adapter

        if (adapter.itemCount == 0) {
            list.visibility = View.GONE
            emptyList.visibility = View.VISIBLE
        }
        else {
            list.visibility = View.VISIBLE
            emptyList.visibility = View.GONE
        }

        val name = "${location.side.toString()} ${location.bodyPart.toString()}"
        view.findViewById<TextView>(R.id.location_name_text).text = name
    }
}
