package com.trace.ar.drawing.fragment;

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

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.trace.ar.drawing.R;
import com.trace.ar.drawing.adapter.FavoriteAdapter;
import com.trace.ar.drawing.databinding.FragmentFavoriteBinding;

import com.trace.ar.drawing.helper.FilePath;
import com.trace.ar.drawing.helper.ObjectBox;
import com.trace.ar.drawing.listener.OnAddOrRemoveListener;
import com.trace.ar.drawing.listener.OnDeleteLikeListener;

import java.util.List;

public class FavoriteFragment extends Fragment {
    private FragmentFavoriteBinding binding;

    public FavoriteFragment() {

    }
    public static FavoriteFragment newInstance() {
        FavoriteFragment fragment = new FavoriteFragment();
        return fragment;
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentFavoriteBinding.inflate(getLayoutInflater());
        onInit();
        return binding.getRoot();
    }

    private void onInit(){
        List<FilePath> filePaths = ObjectBox.queryAllLike();
        FavoriteAdapter favoriteAdapter = new FavoriteAdapter(requireActivity());
        favoriteAdapter.setData(filePaths);
        updateUi(filePaths);
        favoriteAdapter.setListener(new OnDeleteLikeListener() {
            @Override
            public void onDeleteItem(int pos, String path) {

            }
        });
        binding.recyclerview.setAdapter(favoriteAdapter);
        binding.recyclerview.setLayoutManager(new GridLayoutManager(requireContext(), 3));


        ObjectBox.addListener(new OnAddOrRemoveListener() {
            @Override
            public void onAddLike() {
                List<FilePath> filePaths = ObjectBox.queryAllLike();
                favoriteAdapter.setData(filePaths);
                updateUi(filePaths);
            }

            @Override
            public void onDeleteLike() {
                List<FilePath> filePaths = ObjectBox.queryAllLike();
                favoriteAdapter.setData(filePaths);
                updateUi(filePaths);
            }
        });
    }

    private void updateUi(List<FilePath> filePaths){
        if(filePaths.size()>0){
            binding.recyclerview.setVisibility(View.VISIBLE);
            binding.layoutNoFavorite.setVisibility(View.GONE);
        }else {
            binding.recyclerview.setVisibility(View.GONE);
            binding.layoutNoFavorite.setVisibility(View.VISIBLE);
        }

    }
}