package com.prank.funnypranksounds.ui.fragment;

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

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

import com.prank.funnypranksounds.data.local.entity.AudioData;
import com.prank.funnypranksounds.databinding.FragmentCategoryBinding;
import com.prank.funnypranksounds.ui.adapter.AudioAdapter;
import com.prank.funnypranksounds.utils.ItemDecoration;
import com.prank.funnypranksounds.viewmodel.AudioViewModel;

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

public class CategoryFragment extends Fragment {

    private FragmentCategoryBinding binding;
    private AudioAdapter adapter;
    private AudioViewModel audioViewModel;

    @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() {

        audioViewModel = new ViewModelProvider(this,
                new ViewModelProvider.AndroidViewModelFactory(requireActivity().getApplication()))
                .get(AudioViewModel.class);

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

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

    }

    private void initEvent() {
        loadFirstCategory();
    }

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

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