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.FragmentFavoriteBinding;
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 FavoriteFragment extends Fragment {

    private FragmentFavoriteBinding binding;
    private SoundAdapter adapter;
    private HappyViewModel happyViewModel;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentFavoriteBinding.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(), 3));

        adapter = new SoundAdapter(new ArrayList<>(), happyViewModel, requireContext(), 1);
        binding.recyclerView.setAdapter(adapter);

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

    private void initEvent() {
        loadFavorite();
    }

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

    private void updateUIForEmptyData(List<HappyData> dataList) {
        if (dataList.isEmpty()) {
            binding.favoriteText.setVisibility(View.VISIBLE);
        } else {
            binding.favoriteText.setVisibility(View.GONE);
        }
    }

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