package com.adealink.weparty.commonui.viewpager

import androidx.viewpager.widget.ViewPager

/**
 * 参考:https://cloud.tencent.com/developer/article/1742417
 *
 * (ViewPager2无法实现两个ViewPager联动的效果)
 */
class LinkPageChangeListener(private val selfViewPager: ViewPager, private val linkViewPager: ViewPager) : ViewPager.OnPageChangeListener {
    private var pos = 0
    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
        val marginX =
            ((selfViewPager.width + selfViewPager.pageMargin) * position + positionOffsetPixels) * (linkViewPager.width + linkViewPager.pageMargin) / (selfViewPager.width + selfViewPager.pageMargin)
        if (linkViewPager.scrollX != marginX) {
            linkViewPager
            linkViewPager.scrollTo(marginX, 0)
        }
    }

    override fun onPageSelected(position: Int) {
        pos = position
    }

    override fun onPageScrollStateChanged(state: Int) {
        if (state == ViewPager.SCROLL_STATE_IDLE) {
            linkViewPager.currentItem = pos
        }
    }
}