package org.mercury_im.messenger.ui.roster.contacts;

import static androidx.constraintlayout.widget.Constraints.TAG;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton;

import butterknife.BindView;
import butterknife.ButterKnife;

import org.mercury_im.messenger.R;

/**
 * A placeholder fragment containing a simple view.
 */
public class ContactListFragment extends Fragment {

    private ContactListViewModel contactListViewModel;

    @BindView(R.id.roster_entry_list__recycler_view)
    RecyclerView recyclerView;
    private final ContactListRecyclerViewAdapter recyclerViewAdapter = new ContactListRecyclerViewAdapter();

    @BindView(R.id.fab)
    ExtendedFloatingActionButton fab;

    public ContactListFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
        ButterKnife.bind(this, view);

        recyclerView.setAdapter(recyclerViewAdapter);

        fab.setOnClickListener(v -> Toast.makeText(getContext(), R.string.not_yet_implemented, Toast.LENGTH_SHORT).show());
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        contactListViewModel = new ViewModelProvider(this).get(ContactListViewModel.class);
        observeViewModel(contactListViewModel);
    }

    private void observeViewModel(ContactListViewModel viewModel) {
        viewModel.getRosterEntryList().observe(this, rosterEntries -> {
            if (rosterEntries == null) {
                Log.d(TAG, "Displaying null roster entries");
                return;
            }
            recyclerViewAdapter.setModels(rosterEntries);
            Log.d(TAG, "Displaying " + rosterEntries.size() + " roster entries");
        });
    }
}
