package com.wallpaper.perfectwallpaper.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.recyclerview.widget.LinearLayoutManager;

import com.wallpaper.perfectwallpaper.adapter.CategoryAdapter;
import com.wallpaper.perfectwallpaper.databinding.FragmentCategoryBinding;
import com.wallpaper.perfectwallpaper.room.ImageEntry;
import com.wallpaper.perfectwallpaper.utils.DatabaseUtils;
import com.wallpaper.perfectwallpaper.utils.ItemDecoration;

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


public class CategoryFragment extends Fragment {

    private FragmentCategoryBinding binding;
    private CategoryAdapter adapter;
    private DatabaseUtils databaseUtils;

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

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


        initData();
        initEvent();

        return binding.getRoot();
    }


    private void initData() {

        databaseUtils = new DatabaseUtils(requireContext());

        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

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

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

    }

    private void initEvent() {
        loadCategoryImage();
    }

    private void loadCategoryImage() {
        databaseUtils
                .getCategoryFirst()
                .observe(getViewLifecycleOwner(), new Observer<List<ImageEntry>>() {
                    @Override
                    public void onChanged(List<ImageEntry> imageEntries) {
                        adapter.updateData(imageEntries);
                    }
                });
    }

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