package com.app.simplitend.chats;

import static com.app.simplitend.chats.ChatFragment.CHAT_ITEM_KEY;

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

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

import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.chats.mvvm.ChatItem;
import com.app.simplitend.chats.mvvm.ChatListViewModel;
import com.app.simplitend.databinding.ChatListFragmentBinding;

public class ChatListFragment extends Fragment implements ChatListAdapter.OnChatItemClickListener {

    // view binding
    protected ChatListFragmentBinding binding;

    // view model
    private ChatListViewModel viewModel;

    public ChatListFragment(){
        // required empty const.
    }

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

        initViews();

        clickEvents();

        return binding.getRoot();
    }

    private void initViews() {

        viewModel = new ViewModelProvider(requireActivity()).get(ChatListViewModel.class);

        binding.chatsRv.setLayoutManager(new LinearLayoutManager(requireActivity()));
        binding.chatsRv.setAdapter(viewModel.getChatListAdapter());

        viewModel.getChatListAdapter().submitList(viewModel.getChatItemList());

        viewModel.getChatListAdapter().setChatItemClickListener(this);
    }

    private void clickEvents() {

        binding.backBtn.setOnClickListener(v -> {
            AppUtil.closeKeyboard(requireActivity());
            Navigation.findNavController(v).popBackStack(R.id.CPDashboardFragment, false, true);
        });

    }

    @Override
    public void onChatItemClick(ChatItem chatItem, int position) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(CHAT_ITEM_KEY, chatItem);

        Navigation.findNavController(binding.getRoot()).navigate(R.id.action_chatListFragment_to_chatFragment, bundle);
    }
}
