package org.tm.archive.help; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import org.tm.archive.logsubmit.SubmitDebugLogRepository; import org.tm.archive.util.livedata.LiveDataUtil; import java.util.Optional; public class HelpViewModel extends ViewModel { private static final int MINIMUM_PROBLEM_CHARS = 10; private final MutableLiveData problemMeetsLengthRequirements; private final MutableLiveData categoryIndex; private final LiveData isFormValid; private final SubmitDebugLogRepository submitDebugLogRepository; public HelpViewModel() { submitDebugLogRepository = new SubmitDebugLogRepository(); problemMeetsLengthRequirements = new MutableLiveData<>(); categoryIndex = new MutableLiveData<>(0); isFormValid = LiveDataUtil.combineLatest(problemMeetsLengthRequirements, categoryIndex, (meetsLengthRequirements, index) -> { return meetsLengthRequirements == Boolean.TRUE && index > 0; }); } LiveData isFormValid() { return isFormValid; } void onProblemChanged(@NonNull String problem) { problemMeetsLengthRequirements.setValue(problem.length() >= MINIMUM_PROBLEM_CHARS); } void onCategorySelected(int index) { this.categoryIndex.setValue(index); } int getCategoryIndex() { return Optional.ofNullable(this.categoryIndex.getValue()).orElse(0); } LiveData onSubmitClicked(boolean includeDebugLogs) { MutableLiveData resultLiveData = new MutableLiveData<>(); if (includeDebugLogs) { submitDebugLogRepository.buildAndSubmitLog(result -> resultLiveData.postValue(new SubmitResult(result, result.isPresent()))); } else { resultLiveData.postValue(new SubmitResult(Optional.empty(), false)); } return resultLiveData; } static class SubmitResult { private final Optional debugLogUrl; private final boolean isError; private SubmitResult(@NonNull Optional debugLogUrl, boolean isError) { this.debugLogUrl = debugLogUrl; this.isError = isError; } @NonNull Optional getDebugLogUrl() { return debugLogUrl; } boolean isError() { return isError; } } }