package uz.mobiuz.mobiservice.dev.ui.sdk.history

import android.annotation.SuppressLint
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hannesdorfmann.adapterdelegates4.AdapterDelegate
import kotlinx.android.synthetic.main.item_history_header.view.*
import uz.agr.sdk.coreui.extension.inflate
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.utils.extensions.getDate
import uz.mobiuz.mobiservice.dev.model.Tuple2
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

class HistoryHeaderDelegate : AdapterDelegate<MutableList<Any>>() {
    private val dateParseFormat = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
    private val dateFormat = SimpleDateFormat("dd MMMM", Locale.getDefault())

    override fun isForViewType(items: MutableList<Any>, position: Int) =
        items[position] is Tuple2

    override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder =
        ViewHolder(parent.inflate(R.layout.item_history_header))

    override fun onBindViewHolder(items: MutableList<Any>, position: Int, viewHolder: RecyclerView.ViewHolder, payloads: MutableList<Any>) =
        (viewHolder as ViewHolder).bind(items[position] as Tuple2)

    private inner class ViewHolder(val containerView: View) : RecyclerView.ViewHolder(containerView) {

        @SuppressLint("SetTextI18n")
        fun bind(header: Tuple2) {
            try {
                containerView.tvTitle.text = header.first.getDate(context = containerView.context)
                if (header.second.isNotEmpty() && header.second.length > 4) {
                    if (header.second != "0") {
                        if (header.second[0] == '-') {
                            containerView.tvTotalSum.text = "${header.second[0]} ${header.second.substring(1, header.second.length)}"
                        } else containerView.tvTotalSum.text = header.second
                    }
                }
            } catch (e: ParseException) {
                containerView.tvTitle.text = null
                containerView.tvTotalSum.text = null
            }
        }
    }
}