package com.ar.arsketch.fragment;

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

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

import com.ar.arsketch.adapter.ImageAdapter;
import com.ar.arsketch.databinding.FragmentCategoryBinding;
import com.ar.arsketch.room.AppDatabase;
import com.ar.arsketch.room.ImageEntry;
import com.ar.arsketch.utils.ItemDecoration;

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


public class CategoryFragment extends Fragment {

    private FragmentCategoryBinding binding;
    private static final String ARG_CATEGORY = "category";
    private String category;
    private ImageAdapter adapter;

    public CategoryFragment() {

    }

    public static CategoryFragment newInstance(String category) {
        CategoryFragment fragment = new CategoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_CATEGORY, category);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            category = getArguments().getString(ARG_CATEGORY);
        }
    }

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

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {
        adapter = new ImageAdapter(requireContext(), new ArrayList<>(),requireActivity());
        binding.categoryRecycler.setAdapter(adapter);
        binding.categoryRecycler.setLayoutManager(new GridLayoutManager(getContext(), 2));

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

    private void initEvent() {
        loadFavoriteImages();
    }

    private void loadFavoriteImages() {
        AppDatabase.getInstance(requireContext())
                .imageEntryDao()
                .getImagesByCategoryLive(category)
                .observe(getViewLifecycleOwner(), new Observer<List<ImageEntry>>() {
                    @Override
                    public void onChanged(List<ImageEntry> imageEntries) {
                        adapter.updateData(imageEntries);
                    }
                });
    }

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