package com.ar.artraceartpro.ui.fragment;

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

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

import com.ar.artraceartpro.data.local.entity.ImageData;
import com.ar.artraceartpro.databinding.FragmentFavoriteBinding;
import com.ar.artraceartpro.ui.adapter.ImageRecyclerViewAdapter;
import com.ar.artraceartpro.utils.ItemDecoration;
import com.ar.artraceartpro.viewmodel.ImageViewModel;

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

public class FavoriteFragment extends Fragment {

    private FragmentFavoriteBinding binding;
    private ImageRecyclerViewAdapter adapter;
    private ImageViewModel imageViewModel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = FragmentFavoriteBinding.inflate(inflater, container, false);

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {

        imageViewModel = new ViewModelProvider(requireActivity(), new ViewModelProvider.AndroidViewModelFactory(requireActivity().getApplication()))
                .get(ImageViewModel.class);

        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

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

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

    }

    private void initEvent() {
        loadAllFavorite();
    }

    private void loadAllFavorite() {
        imageViewModel
                .getAllFavorite()
                .observe(getViewLifecycleOwner(), new Observer<List<ImageData>>() {
                    @Override
                    public void onChanged(List<ImageData> imageEntries) {
                        if (imageEntries.isEmpty()) {
                            binding.text.setVisibility(View.VISIBLE);
                        } else {
                            binding.text.setVisibility(View.GONE);
                        }
                        adapter.updateData(imageEntries);
                    }
                });
    }

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