package com.example.vdcscore.ui.livegames;

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

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.vdcscore.R;
import com.example.vdcscore.databinding.FragmentLiveGamesBinding;

public class LiveGamesFragment extends Fragment {

    private FragmentLiveGamesBinding binding;
    private GameViewModel gameViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        gameViewModel = new ViewModelProvider(requireActivity()).get(GameViewModel.class);

        binding = FragmentLiveGamesBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        RecyclerView recyclerView = binding.recyclerLiveGames;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        gameViewModel.getGames().observe(getViewLifecycleOwner(), games -> {
            if (binding == null) return;
            GameAdapter adapter = new GameAdapter(games, game -> {
                gameViewModel.selectGame(game);
                Navigation.findNavController(root).navigate(R.id.action_nav_live_games_to_nav_live_game_detail);
            });
            recyclerView.setAdapter(adapter);
        });

        return root;
    }

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