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

import android.content.Intent
import android.util.Log
import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
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.FragmentCollectBinding
import com.sunny.app.soft.timberkeyboardnew.room.MyDatabase
import com.sunny.app.soft.timberkeyboardnew.tools.AppConstant
import com.sunny.app.soft.timberkeyboardnew.topon.AdManager
import com.sunny.app.soft.timberkeyboardnew.ui.activity.DownloadActivity
import com.sunny.app.soft.timberkeyboardnew.ui.activity.ListActivity
import com.sunny.app.soft.timberkeyboardnew.ui.adapter.SelectAdapter
import com.sunny.app.soft.timberkeyboardnew.ui.listener.OnBgItemClickListener

class CollectFragment :
    BaseFragment() {

    private lateinit var binding: FragmentCollectBinding

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

    override fun initView() {
        super.initView()
        // TODO:  loadAd
        initViewPager()
    }

    private fun initViewPager() {
        val homeViewAdapter = SelectAdapter(requireContext(), object : OnBgItemClickListener {
            override fun onItemClick(position: Int, backgroundEntity: BackgroundEntity) {
                val intent = Intent(requireActivity(), DownloadActivity::class.java)
                intent.putExtra(AppConstant.KEY_EXTRA, backgroundEntity)
                startActivity(intent)
            }

        })
        MyDatabase.myDatabase.BackgroundEntityDao().queryCollect(true).observe(requireActivity()){
            homeViewAdapter.updateData(it)
            if(it.size>0){
                binding.collectionRecyclerView.isVisible = true
                binding.empty.isVisible = false
            }else{
                binding.collectionRecyclerView.isVisible = false
                binding.empty.isVisible = true
            }
            Log.d(App.TAG, "collect update  "+it.size)
        }

        binding.collectionRecyclerView.apply {
            layoutManager = LinearLayoutManager(requireContext()).apply {
                orientation = LinearLayoutManager.VERTICAL
            }
            adapter = homeViewAdapter
        }

    }

    private fun enterList() {
        val intent = Intent(requireContext(), ListActivity::class.java)
        intent.putExtra(AppConstant.KEY_EXTRA, data)
        startActivity(intent)
    }


    fun onShowAd() {
        AdManager.showTopOn(requireActivity()) {
                enterList()

        }


    }


}