package org.mercury_im.messenger.android.ui.chatlist;


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.annotation.NonNull;
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.core.Messenger;
import org.mercury_im.messenger.R;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ChatListFragment extends Fragment implements SearchView.OnQueryTextListener {

    private AndroidChatListViewModel viewModel;

    @BindView(R.id.chat_list__recycler_view)
    RecyclerView recyclerView;
    private final ChatListRecyclerViewAdapter recyclerViewAdapter = new ChatListRecyclerViewAdapter();

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

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(AndroidChatListViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chat_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 onResume() {
        super.onResume();
        observeViewModel();
    }

    private void observeViewModel() {
        viewModel.getChats().observe(this, chatModels -> {
            Log.d(Messenger.TAG, "Displaying " + chatModels.size() + " chats");
            recyclerViewAdapter.setModels(chatModels);
        });
    }

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

    @Override
    public boolean onQueryTextChange(String newText) {
        viewModel.onQueryTextChanged(newText);
        return false;
    }
}
