package com.ardraw.ardrawinggallery.fragment;

import android.os.Bundle;

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

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

import com.ardraw.ardrawinggallery.adapter.GalleryAdapter;
import com.ardraw.ardrawinggallery.databinding.FragmentHomeBinding;
import com.ardraw.ardrawinggallery.room.ArData;
import com.ardraw.ardrawinggallery.util.DatabaseUtil;
import com.ardraw.ardrawinggallery.util.ItemDecoration;

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


public class HomeFragment extends Fragment {
    private FragmentHomeBinding binding;
    private GalleryAdapter adapter;
    private DatabaseUtil databaseUtil;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = FragmentHomeBinding.inflate(inflater, container, false);

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {
        databaseUtil = new DatabaseUtil(requireContext());

        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

        adapter = new GalleryAdapter(new ArrayList<>(), requireContext(), 0);
        binding.recyclerView.setAdapter(adapter);

        ItemDecoration itemDecoration = new ItemDecoration(35, 15, 20);
        binding.recyclerView.addItemDecoration(itemDecoration);
    }

    private void initEvent() {
        loadFirst();
    }

    private void loadFirst() {
        databaseUtil
                .getFirst()
                .observe(getViewLifecycleOwner(), new Observer<List<ArData>>() {
                    @Override
                    public void onChanged(List<ArData> arData) {
                        adapter.updateData(arData);
                    }
                });
    }

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