package com.ardrawing.ardrawingspace.fragment;

import android.os.Bundle;

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.ardrawing.ardrawingspace.R;
import com.ardrawing.ardrawingspace.adapter.SpaceRecyclerViewAdapter;
import com.ardrawing.ardrawingspace.databinding.FragmentFavoriteBinding;
import com.ardrawing.ardrawingspace.room.SpaceEntity;
import com.ardrawing.ardrawingspace.util.ItemDecoration;
import com.ardrawing.ardrawingspace.viewmodel.SpaceViewModel;

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

public class FavoriteFragment extends Fragment {
    private FragmentFavoriteBinding binding;
    private SpaceViewModel viewModel;
    private SpaceRecyclerViewAdapter adapter;

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

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {
        viewModel = new ViewModelProvider(this).get(SpaceViewModel.class);

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

        adapter = new SpaceRecyclerViewAdapter(requireContext(), new ArrayList<>(), 2);
        binding.recyclerView.setAdapter(adapter);

        binding.recyclerView.addItemDecoration(new ItemDecoration(35, 15, 20));
    }

    private void initEvent() {
        loadLike();
    }

    private void loadLike() {
        viewModel
                .getFavorite()
                .observe(getViewLifecycleOwner(), new Observer<List<SpaceEntity>>() {
                    @Override
                    public void onChanged(List<SpaceEntity> spaceEntityList) {
                        if (spaceEntityList.isEmpty()) {
                            binding.text.setVisibility(View.VISIBLE);
                        } else {
                            binding.text.setVisibility(View.GONE);
                        }
                        adapter.updateItems(spaceEntityList);
                    }
                });
    }

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