package com.ar.drawing.ui;

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.ar.drawing.adapter.FavoriteAdapter;
import com.ar.drawing.api.OnFavoriteListener;
import com.ar.drawing.db.DataLocal;
import com.ar.drawing.db.MyDb;
import com.ar.drawing.databinding.FragmentFavoriteBinding;

import java.util.List;

public class Favorite extends Fragment {
    private FragmentFavoriteBinding binding;

    public Favorite() {

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



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentFavoriteBinding.inflate(getLayoutInflater());
        onInit();
        binding.btnImport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HomeActivity fragmentActivity1 = (HomeActivity) requireActivity();
                fragmentActivity1.checkPermission();
            }
        });
        return binding.getRoot();
    }

    private void onInit(){
        List<DataLocal> datumLocals = MyDb.queryAllLike();
        FavoriteAdapter favoriteAdapter = new FavoriteAdapter(requireActivity());
        favoriteAdapter.setData(datumLocals);
        updateUi(datumLocals);

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


        MyDb.addListener(new OnFavoriteListener() {
            @Override
            public void onAddLike() {
                List<DataLocal> datumLocals = MyDb.queryAllLike();
                favoriteAdapter.setData(datumLocals);
                updateUi(datumLocals);
            }

            @Override
            public void onDeleteLike() {
                List<DataLocal> datumLocals = MyDb.queryAllLike();
                favoriteAdapter.setData(datumLocals);
                updateUi(datumLocals);
            }
        });
    }

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

    }
}