package com.ardraw.ardrawingflow.ui.fragment;

import android.os.Bundle;

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

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

import com.ardraw.ardrawingflow.data.database.entity.FlowData;
import com.ardraw.ardrawingflow.databinding.FragmentCategoryBinding;
import com.ardraw.ardrawingflow.ui.adapter.FlowItemAdapter;
import com.ardraw.ardrawingflow.ui.viewmodel.FlowViewModel;
import com.ardraw.ardrawingflow.util.ItemDecoration;

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

public class CategoryFragment extends Fragment {
    private FragmentCategoryBinding binding;
    private FlowViewModel flowViewModel;
    private FlowItemAdapter flowItemAdapter;

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

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {
        flowViewModel = new ViewModelProvider(this).get(FlowViewModel.class);

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

        flowItemAdapter = new FlowItemAdapter(requireContext(), new ArrayList<>(), 0);
        binding.recyclerView.setAdapter(flowItemAdapter);

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

    private void initEvent() {
        loadMinId();
    }

    private void loadMinId() {
        flowViewModel
                .getMinId()
                .observe(getViewLifecycleOwner(), new Observer<List<FlowData>>() {
                    @Override
                    public void onChanged(List<FlowData> arData) {
                        flowItemAdapter.refreshItems(arData);
                    }
                });
    }

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