package com.various.funny.sounds.audio.ui.fragment

import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.various.funny.sounds.audio.databinding.FragmentHomeBinding
import com.various.funny.sounds.audio.helper.ComUtils
import com.various.funny.sounds.audio.helper.ItemSpace
import com.various.funny.sounds.audio.ui.adapter.CategoryAdapter

class HomeFragment : Fragment() {

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

    private lateinit var viewModel: HomeViewModel
    private lateinit var homeBinding: FragmentHomeBinding

    private lateinit var mAdapter: CategoryAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        homeBinding = FragmentHomeBinding.inflate(layoutInflater)
        onInitCAtegory()
        return homeBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this)[HomeViewModel::class.java]
        viewModel.getList().observe(viewLifecycleOwner, Observer {

            mAdapter.updateData(it)
        })

    }

    private fun onInitCAtegory() {
        val i = ComUtils.getScreenWidthPx() - ComUtils.dpToPx(156f) * 2
        val spacePx = i / 3
        mAdapter = CategoryAdapter(requireContext())
        homeBinding.recyclerView.run {
            adapter = mAdapter
            layoutManager = GridLayoutManager(requireContext(), 2)
            addItemDecoration(ItemSpace(spacePx))
            setPadding(spacePx, 0, 0, 0)
        }
    }

}