package com.wallpaper.wallpaperbox.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.StaggeredGridLayoutManager;

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

import com.wallpaper.wallpaperbox.R;
import com.wallpaper.wallpaperbox.data.entity.WallpaperEntity;
import com.wallpaper.wallpaperbox.databinding.FragmentHomeBinding;
import com.wallpaper.wallpaperbox.databinding.FragmentLikeBinding;
import com.wallpaper.wallpaperbox.ui.adapter.WallpaperAdapter;
import com.wallpaper.wallpaperbox.ui.viewmodel.WallpaperViewModel;
import com.wallpaper.wallpaperbox.util.ItemDecoration;

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

public class LikeFragment extends Fragment {
    private FragmentLikeBinding binding;
    private WallpaperAdapter adapter;
    private WallpaperViewModel wallpaperViewModel;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentLikeBinding.inflate(inflater, container, false);
        initData();
        initEvent();
        return binding.getRoot();
    }

    private void initData() {
        wallpaperViewModel = new ViewModelProvider(this).get(WallpaperViewModel.class);

        binding.recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

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

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

    private void initEvent() {
        loadFirstWallpaper();
    }

    private void loadFirstWallpaper() {
        wallpaperViewModel
                .getLike()
                .observe(getViewLifecycleOwner(), new Observer<List<WallpaperEntity>>() {
                    @Override
                    public void onChanged(List<WallpaperEntity> wallpaperEntities) {
                        if (wallpaperEntities.isEmpty()) {
                            binding.text.setVisibility(View.VISIBLE);
                        } else {
                            binding.text.setVisibility(View.GONE);
                        }
                        adapter.updateData(wallpaperEntities);
                    }
                });
    }

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