package com.prank.happypranksounds.ui.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.prank.happypranksounds.data.entity.HappyData;
import com.prank.happypranksounds.databinding.FragmentCategoryBinding;
import com.prank.happypranksounds.ui.adapter.SoundAdapter;
import com.prank.happypranksounds.ui.viewmodel.HappyViewModel;
import com.prank.happypranksounds.util.ItemDecoration;

import java.util.ArrayList;
import java.util.List;

public class CategoryFragment extends Fragment {

    private FragmentCategoryBinding binding;
    private SoundAdapter adapter;
    private HappyViewModel happyViewModel;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentCategoryBinding.inflate(inflater, container, false);

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {

        happyViewModel = new ViewModelProvider(this).get(HappyViewModel.class);

        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        adapter = new SoundAdapter(new ArrayList<>(), happyViewModel, requireContext(), 0);
        binding.recyclerView.setAdapter(adapter);

        ItemDecoration itemDecoration = new ItemDecoration(16, 19, 10);
        binding.recyclerView.addItemDecoration(itemDecoration);
    }

    private void initEvent() {
        loadFirstCategory();
    }

    private void loadFirstCategory() {
        happyViewModel
                .getFirstCategory()
                .observe(getViewLifecycleOwner(), new Observer<List<HappyData>>() {
                    @Override
                    public void onChanged(List<HappyData> happyDataList) {
                        if (happyDataList != null) {
                            adapter.updateData(happyDataList);
                        }
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}