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

import android.content.Intent
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.sunny.app.soft.timberkeyboardnew.App
import com.sunny.app.soft.timberkeyboardnew.R
import com.sunny.app.soft.timberkeyboardnew.data.entity.CategoryEntity
import com.sunny.app.soft.timberkeyboardnew.databinding.FragmentHomeBinding
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.ListActivity
import com.sunny.app.soft.timberkeyboardnew.ui.adapter.HomeViewAdapter
import com.sunny.app.soft.timberkeyboardnew.ui.listener.OnItemClickListener

class HomeFragment :
    BaseFragment() {

    private lateinit var binding: FragmentHomeBinding

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

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

    private fun initViewPager() {
        val homeViewAdapter = HomeViewAdapter(requireContext(), object : OnItemClickListener {
            override fun onItemClick(position: Int, categoryEntity: CategoryEntity) {
                data = categoryEntity
                onShowAd()


            }
        })
        MyDatabase.myDatabase.CategoryEntityDao().queryAll().observe(requireActivity()){
            homeViewAdapter.updateData(it)
            Log.d(App.TAG, "CategoryEntityDao  "+it.size)
        }

        binding.homeRecyclerView.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()

        }


    }

    private fun initTitle() {
        binding.homeTitle.text = App.appContext.getString(R.string.app_name)
    }
}