package com.jachdev.consumerprotection.ui.bot;

import android.util.Log;

import com.jachdev.consumerprotection.AppApplication;
import com.jachdev.consumerprotection.data.AppResponse;
import com.jachdev.consumerprotection.data.BotMessage;
import com.jachdev.consumerprotection.data.BotResponse;
import com.jachdev.consumerprotection.data.LipidProfile;
import com.jachdev.consumerprotection.network.AppService;
import com.jachdev.consumerprotection.util.BaseViewModel;
import com.jachdev.consumerprotection.util.SessionManager;

import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.List;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class BotViewModel extends BaseViewModel {


    private static final String TAG = BotViewModel.class.getSimpleName();
    private AppService service;
    private AppService botService;
    private SessionManager manager;
    private MutableLiveData<BotMessage> data = new MutableLiveData<>();
    private MutableLiveData<BotMessage> senderData = new MutableLiveData<>();

    public BotViewModel() {
        manager = SessionManager.getInstance();
        botService = AppApplication.getInstance().getBotService();
        service = AppApplication.getInstance().getAppService();
    }

    public LiveData<BotMessage> getBotMessage() {
        return data;
    }

    public LiveData<BotMessage> getSenderMessage() {
        return senderData;
    }

    public void sendMessage(String message) {
        String uid = manager.getUser().getUid();

        //init sender message
        BotMessage msg = new BotMessage(uid, message);
        msg.setSenderResponse();
        senderData.postValue(msg);

        //Send message to bot
        botService.getBotServer().getMessage(
                msg.getBrainId(), msg.getApiKey(), msg.getUid(), msg.getMessage()
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<BotResponse>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {
                        Log.d(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onSuccess(@NotNull BotResponse response) {

                        BotMessage botMessage = new BotMessage();
                        botMessage.setBotResponse(response);

                        data.postValue(botMessage);
                    }

                    @Override
                    public void onError(@NotNull Throwable e) {

                        data.postValue(null);
                    }
                });
    }
}