package com.jachdev.consumerprotection.ui.camera;

import android.util.Log;

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

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 CameraViewModel extends BaseViewModel {


    private static final String TAG = CameraViewModel.class.getSimpleName();
    private AppService service;
    private MutableLiveData<List<LipidProfile>> data = new MutableLiveData<>();

    public CameraViewModel() {
        service = AppApplication.getInstance().getAppService();
    }

    public LiveData<List<LipidProfile>> getLipidProfile() {
        return data;
    }

    public LiveData<List<LipidProfile>> addLipidProfile(LipidProfile profile) {

        service.getServer().addLipidProfile(profile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<AppResponse>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {
                        Log.d(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onSuccess(@NotNull AppResponse response) {
                        switch (response.getCode()){
                            case 0:
                                List<LipidProfile> profiles = Arrays.asList(response.getObjectToType(LipidProfile[].class).clone());
                                data.postValue(profiles);
                                break;
                            default:
                                data.postValue(null);
                                showMessage(response.getMessage());
                                break;
                        }
                    }

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

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