# RateTheAppViewModel.kt

    /*
     * The MIT License
     *
     * Original work sponsored and donated by The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     * Copyright (C) 2021 The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     *
     * Permission is hereby granted, free of charge, to any person obtaining a copy of
     * this software and associated documentation files (the "Software"), to deal in
     * the Software without restriction, including without limitation the rights to
     * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
     * of the Software, and to permit persons to whom the Software is furnished to do
     * so, subject to the following conditions:
     *
     *
     * The above copyright notice and this permission notice shall be included in all
     * copies or substantial portions of the Software.
     *
     *
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     * SOFTWARE.
     */

    package dk.nsp.mingraviditet.ui.main.more.rating

    import androidx.lifecycle.LiveData
    import androidx.lifecycle.MediatorLiveData
    import androidx.lifecycle.MutableLiveData
    import androidx.lifecycle.ViewModel
    import androidx.lifecycle.viewModelScope
    import com.commonsense.android.kotlin.base.extensions.coroutines.launchIO
    import dagger.hilt.android.lifecycle.HiltViewModel
    import dk.nsp.domain.repository.FeedbackRepository
    import dk.nsp.mingraviditet.util.extensions.toSingleEvent
    import dk.nsp.mingraviditet.util.livedata.SingleEvent
    import dk.nsp.models.FeedbackEntity
    import dk.nsp.shared.Failed
    import dk.nsp.shared.ResultWrapper
    import timber.log.Timber
    import javax.inject.Inject

    @HiltViewModel
    class RateTheAppViewModel @Inject constructor(
        private val feedbackRepository: FeedbackRepository
    ) : ViewModel() {

        private val _ratingSection = MutableLiveData<RatingSection>()
        val ratingSection: LiveData<RatingSection> = _ratingSection

        private val _onRatingSent = MutableLiveData<SingleEvent<ResultWrapper<Unit>>>()
        val onRatingSent: LiveData<SingleEvent<ResultWrapper<Unit>>> = _onRatingSent

        private val _rating = MutableLiveData<Int?>()
        private val _comment = MutableLiveData<String>()

        val ratingCombined = MediatorLiveData<FeedbackEntity>().apply {
            addSource(_rating) { rating ->
                postValue(FeedbackEntity(_comment.value ?: "", rating))
            }
            addSource(_comment) { comment ->
                postValue(FeedbackEntity(comment, _rating.value))
            }
        }

        init {
            _ratingSection.postValue(
                createRatingSection()
            )
        }

        private fun createRatingSection() = RatingSection(
            RatingSectionData(
                ratingCombined.value?.rating,
                ratingCombined.value?.comment,
                ::onRatingChanged,
                ::onCommentChanged,
                ::onSendAppRating
            )
        )

        private fun onRatingChanged(rating: Int?) {
            _rating.postValue(rating)
        }

        private fun onCommentChanged(comment: String) {
            _comment.postValue(comment)
        }

        private fun onSendAppRating() {
            ratingCombined.value?.let {
                viewModelScope.launchIO {
                    val ratingRes = feedbackRepository.sendRating(this, it).await()
                    // Recreate rating session to re-enable the send button
                    if (ratingRes is Failed) {
                        _ratingSection.postValue(createRatingSection())
                        Timber.e(ratingRes.error, "Could not send rating.")
                    }

                    _onRatingSent.postValue(ratingRes.toSingleEvent())
                }
            }
        }
    }