package com.wallpaper.perfectwallpaper.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.wallpaper.perfectwallpaper.adapter.ImageAdapter;
import com.wallpaper.perfectwallpaper.databinding.FragmentHomeCategoryBinding;
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 HomeCategoryFragment extends Fragment {

    private FragmentHomeCategoryBinding binding;
    private static final String ARG_CATEGORY = "type";
    private int type;
    private ImageAdapter adapter;
    private DatabaseUtils databaseUtils;

    public HomeCategoryFragment() {

    }

    public static HomeCategoryFragment newInstance(Integer type) {
        HomeCategoryFragment fragment = new HomeCategoryFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_CATEGORY, type);
        fragment.setArguments(args);
        return fragment;
    }

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

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

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData(){

        databaseUtils = new DatabaseUtils(requireContext());

        adapter = new ImageAdapter(requireContext(), new ArrayList<>(),requireActivity());
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

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

    }
    private void initEvent(){

        loadImages();

    }

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

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