package com.atmob.voiceai.module.cloning;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;

import com.atmob.app.lib.base.BaseViewModel;
import com.atmob.app.lib.livedata.SingleLiveEvent;
import com.atmob.voiceai.data.repositories.CloneRepository;

import javax.inject.Inject;

import dagger.hilt.android.lifecycle.HiltViewModel;


@HiltViewModel
public class VoiceCloningViewModel extends BaseViewModel {

    private final SingleLiveEvent<?> finishEvent = new SingleLiveEvent<>();
    private final CloneRepository cloneRepository;

    private final Observer<Integer> cloneUploadStateObserver;

    @Inject
    public VoiceCloningViewModel(CloneRepository cloneRepository) {
        this.cloneRepository = cloneRepository;
        cloneUploadStateObserver = state -> {
            if (state == null) {
                return;
            }
            if (state == CloneRepository.UploadState.UPLOAD_SUCCESS || state == CloneRepository.UploadState.ERROR) {
                finishEvent.call();
            }
        };
        cloneRepository.getCloneUploadState().observeForever(cloneUploadStateObserver);
    }

    public LiveData<?> getFinishEvent() {
        return finishEvent;
    }

    public LiveData<Integer> getCloneUploadState() {
        return cloneRepository.getCloneUploadState();
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        cloneRepository.getCloneUploadState().removeObserver(cloneUploadStateObserver);
    }
}
