package app.furmeet.events.system.schedule.adapters

import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import app.furmeet.events.system.helper.*
import app.furmeet.events.bff.R
import app.furmeet.events.system.schedule.abstractDataTypes.convention.Convention
import app.furmeet.events.system.schedule.viewHolders.RecyclerViewHolder
import app.furmeet.events.bff.databinding.FragmentRulesItemBinding

class ConventionRulesAdapter(convention: Convention, val activity: Activity) : RecyclerViewAdapter() {
    val data = listOf(
            fun(context: Context) = Pair(context.getString(R.string.convention_rules), convention.rules.solved!!.toHtml())
    ) + convention.additionalRules.map {
        fun(_: Context) = Pair(it.names.solved!!, it.rules.solved!!.toHtml())
    }

    override fun getItemCount(): Int = data.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder =
            RecyclerViewHolder(FragmentRulesItemBinding.inflate(parent.context.layoutInflater).apply {
                val postAnimation = Runnable {
                    expandable.postOnAnimation {
                        doAsync {
                            Thread.sleep(expandable.duration.toLong() + 100)
                            activity.uiThread {
                                expandIcon.setImageResource(
                                        if (expandable.isCollapsed) {
                                            R.drawable.ic_expand_more_black_24dp
                                        } else {
                                            R.drawable.ic_expand_less_black_24dp
                                        }
                                )
                                fulltext.setTextIsSelectable(!expandable.isCollapsed)
                            }
                        }
                    }
                }
                val toggleRunner = Runnable {
                    expandIcon.setImageResource(R.drawable.ic_more_horiz_black_24dp)
                    expandable.toggle(true)
                    postAnimation.run()
                }
                expandBar.setOnClickListener { toggleRunner.run() }
                expandable.setOnClickListener {
                    if (expandable.isCollapsed) {
                        toggleRunner.run()
                    }
                }
                collapser.setOnClickListener {
                    if (!expandable.isCollapsed) {
                        toggleRunner.run()
                    }
                }
            }.root)

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
        FragmentRulesItemBinding.bind(holder.itemView).apply {
            val item = data[position](root.context)
            ruleTitle.text = item.first
            fulltext.text = item.second
        }
    }
}