package com.ar.imagetracear.fragment;

import android.content.Context;
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.GridLayoutManager;


import com.ar.imagetracear.databinding.FragmentCollectionBinding;
import com.ar.imagetracear.database.AppDatabase;
import com.ar.imagetracear.database.ImageTraceEntry;
import com.ar.imagetracear.adapter.SubListAdapter;
import com.ar.imagetracear.utils.ItemDecoration;

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

public class CollectionFragment extends Fragment {
    private FragmentCollectionBinding viewBinding;
    private SubListAdapter imageAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) {
        viewBinding = FragmentCollectionBinding.inflate(inflater, container, false);

        initGridList();
        retrieveFavorites();

        return viewBinding.getRoot();
    }

    private void initGridList() {
        Context context = requireContext();
        viewBinding.recyclerview.setLayoutManager(new GridLayoutManager(context, 2));

        imageAdapter = new SubListAdapter(context, new ArrayList<>());
        viewBinding.recyclerview.setAdapter(imageAdapter);

        ItemDecoration spacing = new ItemDecoration(16, 19, 10);
        viewBinding.recyclerview.addItemDecoration(spacing);
    }

    private void retrieveFavorites() {
        AppDatabase database = AppDatabase.getInstance(requireContext());
        database.imageTraceEntryDao().getFavorite().observe(getViewLifecycleOwner(), new Observer<List<ImageTraceEntry>>() {
            @Override
            public void onChanged(List<ImageTraceEntry> resultList) {
                updateEmptyHint(resultList);
                imageAdapter.updateEntries(resultList);
            }
        });
    }

    private void updateEmptyHint(List<ImageTraceEntry> items) {
        boolean hasData = items != null && !items.isEmpty();
        viewBinding.backgroundText.setVisibility(hasData ? View.GONE : View.VISIBLE);
    }

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