package com.sunny.app.soft.timberkeyboardnew.ui.activity

import android.content.Intent
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.sunny.app.soft.timberkeyboardnew.App
import com.sunny.app.soft.timberkeyboardnew.data.entity.BackgroundEntity
import com.sunny.app.soft.timberkeyboardnew.data.entity.CategoryEntity
import com.sunny.app.soft.timberkeyboardnew.databinding.ActivitySelectBinding
import com.sunny.app.soft.timberkeyboardnew.room.MyDatabase
import com.sunny.app.soft.timberkeyboardnew.tools.AppConstant
import com.sunny.app.soft.timberkeyboardnew.ui.adapter.SelectAdapter
import com.sunny.app.soft.timberkeyboardnew.ui.listener.OnBgItemClickListener

class ListActivity : BaseActivity(), View.OnClickListener {

    private lateinit var binding: ActivitySelectBinding
    private lateinit var categoryEntity: CategoryEntity
    override fun setRootView(): View {
        binding = ActivitySelectBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        categoryEntity = intent.getSerializableExtra(AppConstant.KEY_EXTRA) as CategoryEntity
        initButton()
        initTitle()
        initRecyclerView()
    }

    private fun initRecyclerView() {
        val selectAdapter =
            SelectAdapter(this,  object : OnBgItemClickListener {
                override fun onItemClick(position: Int, backgroundEntity: BackgroundEntity) {
                    val intent = Intent(this@ListActivity, DownloadActivity::class.java)
                    intent.putExtra(AppConstant.KEY_EXTRA, backgroundEntity)
                    startActivity(intent)
                    Log.e("TAG", "onItemClick: $backgroundEntity")
                }
            })

        MyDatabase.myDatabase.BackgroundEntityDao().queryCateId(categoryEntity.id).observe(this){
            selectAdapter.updateData(it)
            Log.d(App.TAG, "selectAdapter  "+it.size)
        }

        binding.selectRecyclerView.apply {
            layoutManager = GridLayoutManager(this@ListActivity, 1)
            adapter = selectAdapter
        }
    }
    override fun loadAd(): Boolean = true
    private fun initTitle() {
        binding.selectTitle.text = categoryEntity.name
    }

    private fun initButton() {
        binding.selectBack.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.selectBack -> {
                finish()
            }
        }
    }

}