package com.app.simplitend.chats.mvvm;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;

import com.app.simplitend.welcome.welcomepatient.mvvm.models.CallResponse;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ChatViewModel extends ViewModel {

    public static final int MESSAGES_PER_PAGE = 50;

    private final ChatsApiService apiService;

    public ChatViewModel() {
        this.apiService = new Retrofit.Builder()
                .baseUrl("https://simplitendapp.betadelivery.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(ChatsApiService.class);
    }

    public void getRemoteChatList(@NonNull String token,
                                  @NonNull String channel_id, int page_no,
                                  ChatsCallBack chatsCallBack) {
        // loading this page from server
        apiService.getRemoteChatsList(token, channel_id,
                        MESSAGES_PER_PAGE, page_no)
                .enqueue(new Callback<CallResponse<ArrayList<RemoteMessage>>>() {
                    @Override
                    public void onResponse(Call<CallResponse<ArrayList<RemoteMessage>>> call, Response<CallResponse<ArrayList<RemoteMessage>>> response) {
                        if (response.body() != null){
                            if (response.body().status != 200 || response.body().result == null){
                                chatsCallBack.onChatsFailed(new Exception("Response body is null"), "Something went wrong");
                                return;
                            }

                            chatsCallBack.onChatsFetched(response.body().result, page_no);
                        }else{
                            chatsCallBack.onChatsFailed(new Exception("Response body is null"), "Something went wrong");
                        }
                    }

                    @Override
                    public void onFailure(Call<CallResponse<ArrayList<RemoteMessage>>> call, Throwable t) {
                        chatsCallBack.onChatsFailed(t, t.getLocalizedMessage());
                    }
                });
    }

    // interfaces
    public interface ChatsCallBack {
        void onChatsFetched(ArrayList<RemoteMessage> chatsList, int page_no);

        void onChatsFailed(Throwable t, String message);
    }
}
