package com.yidian.common.refresh

import android.content.Context
import android.graphics.drawable.AnimationDrawable
import android.util.AttributeSet
import android.view.View
import android.view.animation.ScaleAnimation
import android.widget.FrameLayout
import android.widget.ImageView
import com.scwang.smart.refresh.layout.api.RefreshHeader
import com.scwang.smart.refresh.layout.api.RefreshKernel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.constant.RefreshState
import com.scwang.smart.refresh.layout.constant.SpinnerStyle
import com.yidian.common.R


class CustomHeader @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyle: Int = 0
) : FrameLayout(context, attributeSet, defStyle) ,RefreshHeader{
    private  val TAG = "CustomHeader"
private var animDrawable:AnimationDrawable
private var imageView:ImageView
    init {
        View.inflate(context, R.layout.layout_refresh, this)
        imageView = findViewById<ImageView>(R.id.iv_loading)
        animDrawable = context.getDrawable(R.drawable.anim_loading) as AnimationDrawable
    }

    override fun getSpinnerStyle(): SpinnerStyle {
        return SpinnerStyle.Translate
    }

    override fun onFinish(refreshLayout: RefreshLayout, success: Boolean): Int {
        return 500
    }

    override fun onInitialized(kernel: RefreshKernel, height: Int, maxDragHeight: Int) {
    }

    override fun onHorizontalDrag(percentX: Float, offsetX: Int, offsetMax: Int) {
    }

    override fun onReleased(refreshLayout: RefreshLayout, height: Int, maxDragHeight: Int) {
    }

    override fun getView(): View {
        return this
    }

    override fun setPrimaryColors(vararg colors: Int) {
    }

    override fun onStartAnimator(refreshLayout: RefreshLayout, height: Int, maxDragHeight: Int) {
        imageView.setImageDrawable(animDrawable)
        animDrawable.start()
    }

    override fun onStateChanged(
        refreshLayout: RefreshLayout,
        oldState: RefreshState,
        newState: RefreshState
    ) {
        if(oldState==RefreshState.RefreshFinish && newState ==RefreshState.None){
            animDrawable.stop()
            animDrawable.selectDrawable(0)
            imageView.setImageResource(R.drawable.icon_pull_to_refresh_header_state_immobile_white)
        }
    }

    private var oldPercent=0f
    override fun onMoving(
        isDragging: Boolean,
        percent: Float,
        offset: Int,
        height: Int,
        maxDragHeight: Int
    ) {
        if(percent<=1f){
            val scaleAnim = ScaleAnimation(oldPercent, percent, oldPercent, percent,imageView.width/2f,imageView.height/2f)
            scaleAnim.fillAfter = true
            scaleAnim.duration=1
            imageView.startAnimation(scaleAnim)
            oldPercent = percent
        }
    }

    override fun isSupportHorizontalDrag(): Boolean {
        return false
    }
}