# RatingSection.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.core.widget.doOnTextChanged
    import com.commonsense.android.kotlin.base.extensions.toEditable
    import com.commonsense.android.kotlin.system.extensions.getColorSafe
    import dk.nsp.mingraviditet.R
    import dk.nsp.mingraviditet.databinding.RateTheAppSectionBinding
    import dk.nsp.mingraviditet.extensions.disable
    import dk.nsp.mingraviditet.util.android.recycler.BindingViewHolder
    import dk.nsp.mingraviditet.util.android.recycler.DelegationListAdapterInflater
    import dk.nsp.mingraviditet.util.android.recycler.RecyclerAdapterView
    import dk.nsp.mingraviditet.util.extensions.getColorFromAttr

    data class RatingSectionData(
        val prefilledRating: Int? = null,
        val prefilledComment: String? = null,
        val ratingChanged: (Int?) -> Unit,
        val onCommentChanged: (String) -> Unit,
        val onSendRating: () -> Unit
    )

    class RatingSection(val model: RatingSectionData) : RecyclerAdapterView<RateTheAppSectionBinding> {
        private var rating: Int? = null
            set(value) {
                field = value
                model.ratingChanged(value)
            }

        private var comment: String = ""
            set(value) {
                field = value
                model.onCommentChanged(value)
            }

        override fun bindData(viewHolder: BindingViewHolder<RateTheAppSectionBinding>) {
            // If backend failed, we recreate the last state here
            model.prefilledRating?.let { rating = it }
            model.prefilledComment?.let { comment = it }

            with(viewHolder.binding) {
                rating1.setOnClickListener { setNewRating(this, 1) }
                rating2.setOnClickListener { setNewRating(this, 2) }
                rating3.setOnClickListener { setNewRating(this, 3) }
                rating4.setOnClickListener { setNewRating(this, 4) }
                rating5.setOnClickListener { setNewRating(this, 5) }
            }

            viewHolder.binding.ratingComment.doOnTextChanged { text, _, _, _ ->
                if (viewHolder.binding.ratingLayout.isErrorEnabled && text?.isNotBlank() == true) {
                    viewHolder.binding.ratingLayout.isErrorEnabled = false
                }
                comment = text?.toString() ?: ""
            }

            viewHolder.binding.sendRatingButton.setOnClickListener {
                val valid = validateInputs(viewHolder.binding)

                if (valid) {
                    model.onSendRating()
                    viewHolder.binding.sendRatingButton.disable()
                }
            }

            updateRatingState(viewHolder.binding)
            updateCommentState(viewHolder.binding)
        }

        private fun updateRatingState(binding: RateTheAppSectionBinding) {
            val buttons = listOf(
                binding.rating1,
                binding.rating2,
                binding.rating3,
                binding.rating4,
                binding.rating5
            )

            buttons.forEachIndexed { index, imageView ->
                if (index + 1 == rating) {
                    imageView.setColorFilter(binding.root.context.getColorFromAttr(R.attr.colorPrimary))
                } else {
                    imageView.setColorFilter(binding.root.context.getColorSafe(R.color.moon_raker))
                }
            }
        }

        private fun updateCommentState(binding: RateTheAppSectionBinding) {
            binding.ratingComment.text = comment.toEditable()
        }

        private fun setNewRating(binding: RateTheAppSectionBinding, rating: Int) {
            this.rating = rating
            updateRatingState(binding)
        }

        private fun validateInputs(binding: RateTheAppSectionBinding): Boolean {
            return if (binding.ratingComment.text?.isBlank() == true) {
                binding.ratingLayout.isErrorEnabled = true
                binding.ratingLayout.error =
                    binding.root.context.getString(R.string.rate_the_app_comment_required)
                false
            } else {
                binding.ratingLayout.isErrorEnabled = false
                true
            }
        }

        override val createHolderFunction: DelegationListAdapterInflater<RateTheAppSectionBinding> =
            RateTheAppSectionBinding::inflate
    }