package com.gh.gamecenter.gamedetail.detail

import android.content.Context
import android.util.AttributeSet
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.view.FixAppBarLayoutBehavior
import com.google.android.material.appbar.AppBarLayout
import kotlin.math.abs

class GameDetailAppBarBehavior @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : FixAppBarLayoutBehavior(context, attrs) {
    private var maxScrollHeight = 0

    override fun setTopAndBottomOffset(offset: Int): Boolean {
        val finalOffset = if (maxScrollHeight > 0 && maxScrollHeight <= abs(offset)) -maxScrollHeight else offset
        return super.setTopAndBottomOffset(finalOffset)
    }

    override fun onLayoutChild(parent: CoordinatorLayout, abl: AppBarLayout, layoutDirection: Int): Boolean {
        calculateMaxScrollHeight(parent, abl)
        return super.onLayoutChild(parent, abl, layoutDirection)
    }

    private fun calculateMaxScrollHeight(parent: CoordinatorLayout, child: AppBarLayout) {
        val recyclerView = parent.findViewById<RecyclerView>(R.id.detailRv) ?: return
        val parentHeight = parent.measuredHeight
        val recyclerViewHeight = recyclerView.measuredHeight
        val childScrollTotalHeight = child.totalScrollRange

        maxScrollHeight = (childScrollTotalHeight - parentHeight + recyclerViewHeight).coerceAtLeast(0)
    }
}