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

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 androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

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

import org.mercury_im.messenger.R;

import butterknife.BindView;
import butterknife.ButterKnife;

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

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

    private AndroidContactListViewModel viewModel;

    @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 void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(AndroidContactListViewModel.class);
    }

    @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 -> displayAddContactDialog());
        return view;
    }

    private void displayAddContactDialog() {
        AddContactDialogFragment addContactDialogFragment = new AddContactDialogFragment(viewModel.getAccounts().getValue(), viewModel.getMessenger());
        addContactDialogFragment.show(this.getParentFragmentManager(), "add");
    }

    @Override
    public void onResume() {
        super.onResume();
        observeViewModel(viewModel);
    }

    private void observeViewModel(AndroidContactListViewModel 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");
        });
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        viewModel.onContactSearchQueryTextChanged(newText);
        return true;
    }
}
