package com.cooleshow.teacher.helper;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.view.View;
import android.view.animation.LinearInterpolator;

import java.util.ArrayList;

/**
 * Author by pq, Date on 2022/4/7.
 */
public class LiveRoomAnimatorHelper {
    private volatile static LiveRoomAnimatorHelper mHelper;
    private ArrayList<View> animaViews = new ArrayList<>();
    private ArrayList<AnimatorSet> animations = new ArrayList<>();


    private LiveRoomAnimatorHelper() {

    }

    public static LiveRoomAnimatorHelper getInstance() {
        if (mHelper == null) {
            synchronized (LiveRoomAnimatorHelper.class) {
                if (mHelper == null) {
                    mHelper = new LiveRoomAnimatorHelper();
                }
            }
        }
        return mHelper;
    }

    public void startBarrageViewAnimation(Context context, View targetView) {
        targetView.setVisibility(View.VISIBLE);
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(targetView, "translationX", -300, 0f);
        ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(targetView, "alpha", 0.2f, 1f);
        AnimatorSet animatorSet = new AnimatorSet();
        LinearInterpolator linearInterpolator = new LinearInterpolator();
        animatorSet.setInterpolator(linearInterpolator);
        animatorSet.play(objectAnimator).with(objectAnimator2);
        animatorSet.setDuration(1000);
        animatorSet.start();
        animaViews.add(targetView);
        animations.add(animatorSet);
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (animaViews != null) {
                    animaViews.remove(targetView);
                }
                if (animations != null) {
                    animations.remove(animatorSet);
                }
            }
        });
    }

    public void releaseAnimator() {
        if (animaViews != null) {
            for (int i = 0; i < animaViews.size(); i++) {
                View view = animaViews.get(i);
                view.clearAnimation();
            }
        }
        if (animations != null) {
            for (int i = 0; i < animations.size(); i++) {
                AnimatorSet animatorSet = animations.get(i);
                animatorSet.cancel();
                animatorSet = null;
            }
        }
    }


}
