package com.wall.photography.wallpaper.fragment

import android.content.Intent
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.wall.photography.wallpaper.MyApp
import com.wall.photography.wallpaper.R
import com.wall.photography.wallpaper.activivty.ListActivity
import com.wall.photography.wallpaper.adapter.AdapterCategory
import com.wall.photography.wallpaper.databinding.FragmentCategoryBinding
import com.wall.photography.wallpaper.databinding.FragmentHomeBinding
import com.wall.photography.wallpaper.manager.MyItemDecoration
import com.wall.photography.wallpaper.topon.AdManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class CategoryFragment : Fragment() {

    companion object {
        fun newInstance() = CategoryFragment()
    }

    private var viewModel: CategoryViewModel? = null
    private lateinit var vb: FragmentCategoryBinding
    private lateinit var mAdapter: AdapterCategory
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        vb = FragmentCategoryBinding.inflate(layoutInflater)
        return vb.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this)[CategoryViewModel::class.java]
        CoroutineScope(Dispatchers.IO).launch {
            viewModel?.getData()
        }
        mAdapter = AdapterCategory(requireContext()) {
            AdManager.showTopOn(requireActivity()) {
                startActivity(Intent(requireActivity(), ListActivity::class.java).apply {
                    putExtra(ListActivity.KEY, it.cateName)
                })
            }
        }

        viewModel?.data?.observe(requireActivity()) {
            Log.d(MyApp.TAG, "----------category ${it.size}- ${Thread.currentThread().name}")
            mAdapter.updateData(it)
        }

        vb.categoryRecycler.run {
            adapter = mAdapter
            layoutManager = GridLayoutManager(requireContext(), 2)
            addItemDecoration(MyItemDecoration(requireContext(), 8, 8, 0))
        }
    }

    fun refreshCate() {
        CoroutineScope(Dispatchers.IO).launch {
            viewModel?.getData()
        }
    }

}