package com.khmer9.yuki.screen.main

import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.gdtlib.lib.adapter.BaseListItem
import com.gdtlib.lib.viewholder.BaseListViewHolder
import com.google.android.material.card.MaterialCardView
import com.khmer9.yuki.R
import com.khmer9.yuki.extension.btnClick
import com.khmer9.yuki.extension.setSafeOnClickListener
import com.khmer9.yuki.remote.ModuleData
import com.squareup.picasso.Picasso

class MainModuleViewHolder(itemView: View, private val detailButtonListener: ((String, String, Int) -> Unit)? = null) : BaseListViewHolder(itemView) {
    private val picasso = Picasso.get()

    override fun bindView(item: BaseListItem) {
        val imgIcon = itemView.findViewById<ImageView>(R.id.img_icon)
        val tvName = itemView.findViewById<TextView>(R.id.tv_name)
        val itemModule = itemView.findViewById<MaterialCardView>(R.id.item_module)

        if (item is ModuleData) {
            tvName.text = item.name

            try {
                val displayMetrics = itemView.context.resources.displayMetrics
                val pxWidth = displayMetrics.widthPixels
                val pxHeight = displayMetrics.heightPixels
                val dpWidth = pxWidth / displayMetrics.density
                val dpHeight = pxHeight / displayMetrics.density

                // high resolution pixel 14400
                var height = dpHeight * 0.5804f

                //low resolution
                if (pxWidth < 1000) {
                    height = dpHeight * 0.2804f
                }

                imgIcon.layoutParams.height = height.toInt()
                imgIcon.layoutParams.width = height.toInt()

                picasso
                    .load(item.smallIcon)
                    .placeholder(R.drawable.animal_seven)
                    .into(imgIcon)
            } catch (e: Exception) {
            }

            itemModule.setSafeOnClickListener {
                it.btnClick().subscribe {
                    detailButtonListener?.invoke(item.id, item.appId, item.numberSub)
                }
            }
        }
    }
}