package com.gh.gamecenter.common.view

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.core.utils.DisplayUtils
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.header.TwoLevelHeader

class HomeTwoLevelHeader @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : TwoLevelHeader(context, attrs) {

    private val mShowTwoLevelStartOffset = 139F.dip2px() - DisplayUtils.getStatusBarHeight(context.resources)
    private var mOffset = 0

    @SuppressLint("RestrictedApi")
    override fun onMoving(isDragging: Boolean, percent: Float, offset: Int, height: Int, maxDragHeight: Int) {
        moveSpinner(offset)
        val refreshHeader = mRefreshHeader
        val refreshKernel = mRefreshKernel
        refreshHeader?.onMoving(isDragging, percent, offset, height, maxDragHeight)
        if (isDragging) {
            if (mShowTwoLevelStartOffset in (mOffset + 1)..offset && mEnableTwoLevel) {
                refreshKernel.setState(RefreshState.ReleaseToTwoLevel)
            } else if (mOffset >= mShowTwoLevelStartOffset && percent < mRefreshRate) {
                refreshKernel.setState(RefreshState.PullDownToRefresh)
            } else if (mShowTwoLevelStartOffset in (offset + 1)..mOffset && mEnableFloorRefresh) {
                refreshKernel.setState(RefreshState.ReleaseToRefresh)
            } else if (!mEnableFloorRefresh && refreshKernel.refreshLayout.state != RefreshState.ReleaseToTwoLevel) {
                refreshKernel.setState(RefreshState.PullDownToRefresh)
            }
            mPercent = percent
            mOffset = offset
        }
    }
}