package de.sebse.fuplanner2.ui.courses

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import de.sebse.fuplanner2.R
import de.sebse.fuplanner2.database.Course
import de.sebse.fuplanner2.ui.CaptionHolder
import de.sebse.fuplanner2.ui.CustomHolder
import de.sebse.fuplanner2.ui.ListItemHolder
import de.sebse.fuplanner2.ui.ViewHolderGenerator
import de.sebse.fuplanner2.utils.cast
import java.util.*

class CoursesAdapter(private val onclick: (Course) -> Unit) : RecyclerView.Adapter<CustomHolder>() {

    private val positionalData: ArrayList<Any> = arrayListOf()
    var dataset: List<Course> = listOf()
    set(value) {
        field = value
        positionalData.clear()
        var last: Course? = null
        dataset.forEach {
            if (last?.let { last -> it < last } != false)
                positionalData.add(Pair(it.isSummerSemester, it.year))
            positionalData.add(it)
            last = it
        }
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomHolder {
        return ViewHolderGenerator.getHolderByType(parent, viewType)
    }

    override fun onBindViewHolder(holder: CustomHolder, position: Int) {
        // val viewType = getItemViewType(position)
        val res = holder.itemView.resources
        when (holder) {
            is CaptionHolder -> cast<Pair<Boolean, Int?>>(positionalData[position])?.let { (isSummer, year) ->
                holder.string.text = when {
                    year == null -> res.getString(R.string.projects)
                    isSummer -> res.getString(R.string.summer_semester, year)
                    else -> res.getString(R.string.winter_semester, year, year+1)
                }
            }
            is ListItemHolder -> cast<Course>(positionalData[position])?.let {
                holder.title.text = it.title
                holder.subLeft.text = it.lecturers.filter { lecturer -> lecturer.isResponsible }.joinToString { lecturer ->
                    res.getString(R.string.full_name, lecturer.fistName.substring(0, 1)+".", lecturer.lastName)
                }
                holder.subRight.text = it.type
                holder.itemView.setOnClickListener { _ -> this.onclick(it) }
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return when (positionalData[position]) {
            is Course -> ViewHolderGenerator.HolderType.ITEM.ordinal
            else -> ViewHolderGenerator.HolderType.HEADER.ordinal
        }
    }

    // Return the size of your dataset (invoked by the layout manager)
    override fun getItemCount() = positionalData.size
}
