package melody.offline.music.view

import android.annotation.SuppressLint
import android.content.Context
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.json.JSONObject
import melody.offline.music.R
import melody.offline.music.adapter.ResponsiveListAdapter
import melody.offline.music.innertube.Innertube
import melody.offline.music.innertube.models.MusicCarouselShelfRenderer
import melody.offline.music.util.AnalysisUtil
import melody.offline.music.util.LogTag

@SuppressLint("ViewConstructor")
class MusicResponsiveListView(context: Context, homePage: Innertube.HomePage) :
    ModuleView(context) {

    private var adapter: ResponsiveListAdapter? = null

    init {
        contentView = inflate(getContext(), R.layout.music_list_layout, this)
        val title = contentView?.findViewById<TextView>(R.id.title)
        title?.text = homePage.title

        val rv = contentView?.findViewById<RecyclerView>(R.id.rv)

        adapter = ResponsiveListAdapter(context, homePage.contents)
        adapter?.setOnItemClickListener(object : ResponsiveListAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                val jsonObject = JSONObject()
                jsonObject.put("moduleName", homePage.title)
                val map = mutableMapOf(Pair(AnalysisUtil.PARAM_VALUE, jsonObject.toString()))
                AnalysisUtil.logEvent(AnalysisUtil.HOME_B_MODULE_CLICK, map)
            }
        })
        adapter?.setOnItemMoreClickListener(object : ResponsiveListAdapter.OnItemMoreClickListener {
            override fun onItemMoreClick(position: Int) {
                val bean = homePage.contents[position]
                if (moreClickListener != null) {
                    moreClickListener?.onMoreClick(bean)
                }
            }
        })
        rv?.layoutManager = GridLayoutManager(context, 3, GridLayoutManager.HORIZONTAL, false)
        rv?.adapter = adapter
    }

    @SuppressLint("NotifyDataSetChanged")
    fun updateAdapter() {
        if (adapter != null) {
            adapter?.notifyDataSetChanged()
        }
    }

    private var moreClickListener: OnMoreClickListener? = null

    fun setOnItemMoreClickListener(listener: OnMoreClickListener) {
        moreClickListener = listener
    }

    interface OnMoreClickListener {
        fun onMoreClick(bean: MusicCarouselShelfRenderer.Content)
    }
}