package bums.lunatic.launcher.home.adapters

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import bums.lunatic.launcher.databinding.ItemHourlyWeatherBinding
import bums.lunatic.launcher.model.Hour
import bums.lunatic.launcher.model.WeatherInfoManager
import bums.lunatic.launcher.utils.BLog
import com.squareup.picasso.Picasso

class WeatherHourlyAdapter(private val dataSet: ArrayList<Hour>): RecyclerView.Adapter<WeatherHourlyAdapter.ViewHolder>() {
    class ViewHolder(val viewItem: ItemHourlyWeatherBinding): RecyclerView.ViewHolder(viewItem.root)

    override fun onCreateViewHolder(parent: ViewGroup, type: Int): WeatherHourlyAdapter.ViewHolder {
        val binding = ItemHourlyWeatherBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return WeatherHourlyAdapter.ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data = dataSet[position] as? Hour
//        BLog.LOGE("saved weatherForcast >>> asFlow ${dataSet.size}")
        data?.let {
            WeatherInfoManager.getShowingInfo(it).apply {
                holder.viewItem.setInfo(this)
                Picasso.get()
                    .load(this.urlImgWeather)
                    .into(holder.viewItem.imgWeather)
            }
//            BLog.LOGE("reeeeeeeeeee >>> ${holder.viewItem.hour.text}")
            holder.viewItem.amOrPm.visibility =
                if (arrayListOf(12, 0).contains(WeatherInfoManager.toZonedDateTime(it.time_epoch).hour) || position == 0) {
                    View.VISIBLE
                } else View.INVISIBLE
            holder.viewItem.hour.apply {
                if (WeatherInfoManager.toZonedDateTime(it.time_epoch).hour == 0) {
                    this@apply.setTextColor(Color.BLACK)
                    this@apply.isSelected = true
                } else {
                    this@apply.setTextColor(Color.WHITE)
                    this@apply.isSelected = false
                }
            }
        }
    }

    override fun getItemCount(): Int = dataSet.size

    fun update(li: Collection<Hour>) {
        BLog.LOGE("${this.javaClass.simpleName}  update")
        li.toList()
        this.dataSet.clear()
        this.dataSet.addAll(li)
    }
}