package com.bokecc.livemodule.view.redpacket;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;

import com.bokecc.dwlivedemo.R;
import com.bokecc.sdk.mobile.live.pojo.RedPacketInfo;

import java.util.ArrayList;
import java.util.List;

import static com.bokecc.livemodule.view.redpacket.RedPacketRes.TYPE_GIFT;

import androidx.annotation.NonNull;


/**
 * 红包雨动画帮助类。
 * 业务代码，保持直播间整洁而抽离。
 * <p>
 * Created on 2021/7/2.
 *
 * @author zzw
 */

public class RedPacketViewHelper {
    private TextureView mRedPacketView; //红包雨承载控件（为保持扩展性，未对该View进行自定义）。
    private RedPacketAnimView mRedPacketAnimView;
    private ViewGroup viewGroup;
    private RedPacketRender mRedPacketRender; //红包雨渲染器。
    private boolean mIsRuning; //是否在下红包雨（用于规避同时下多场红包雨）。
    private RedPacketStateListener mRedPacketStateListener; //红包雨监听器。
    private String redPacketId;//红包雨id
    private String liveId;//直播id
    //触摸监听  用于拦截点击事件打开红包并且防止点击事件透传
    private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                BoxInfo boxInfo = mRedPacketRender.getClickPosition((int) event.getRawX(), (int) event.getRawY(), TYPE_GIFT);
                if (boxInfo != null) {
                    openGift(boxInfo);
                }
            }
            return true;
        }
    };
    private Activity context;
    private int time;
    private Handler handler = new Handler(Looper.getMainLooper());
    private RedPacketAnimRunnable redPacketAnimRunnable;//绘制红包雨延迟消息
    private RedPacketDelayDestroyRunnable redPacketDelayDestroyunnable;//延迟销毁红包雨 防止断网丢包情况
    //红包雨监听
    private RedPacketRender.OnStateChangeListener onStateChangeListener = new RedPacketRender.OnStateChangeListener() {
        @Override
        public void onRun() {
            if (mRedPacketView == null || context == null || context.isFinishing()) {
                return;
            }
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mRedPacketView.setVisibility(View.VISIBLE);
                    if (mRedPacketStateListener != null) {
                        mRedPacketStateListener.onStart();
                    }
                }
            });
        }

        @Override
        public synchronized void onEnd(final boolean isCallBack) {
            if (context == null || context.isFinishing()) {
                return;
            }
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (isCallBack){
                        if (mRedPacketStateListener != null) {
                            mRedPacketStateListener.onEnd(redPacketId);
                        }
                    }

                    if (viewGroup!=null&&mRedPacketAnimView!=null){
                        viewGroup.removeView(mRedPacketAnimView);
                        mRedPacketAnimView = null;
                    }
                    if (mRedPacketView != null) {
                        mRedPacketView.setVisibility(View.GONE);
                        mRedPacketView.setSurfaceTextureListener(null);
                        if (viewGroup != null) {
                            viewGroup.removeView(mRedPacketView);
                        }
                        mRedPacketView = null;
                        mRedPacketRender = null;
                        //在所有红包雨的引用断开后，才置为false。
                        mIsRuning = false;
                        redPacketId = null;
                        liveId = null;
                        Log.i("xyz", "gift rain remove textureView");
                    }
                }
            });
        }
    };;


    public boolean isRuning() {
        return mIsRuning;
    }

    /**
     * 设置红包雨监听器
     */
    public void setGiftRainListener(RedPacketStateListener mRedPacketStateListener) {
        this.mRedPacketStateListener = mRedPacketStateListener;
    }

    /**
     * 开始红包雨。
     *
     * @param redPacketInfo    红包雨
     * @param context 上下文
     * @return 是否成功发射（只管有没有成功发射，不管最终是否顺利执行）。
     */
    public boolean startRedPacket(RedPacketInfo redPacketInfo, Activity context) {
        if (mIsRuning) {
            return false;
        }
        if (redPacketInfo == null){
            return false;
        }
        if (redPacketInfo.getDuration() == 0) {
            return false;
        }
        this.context=context;
        mIsRuning = true;
        this.redPacketId = redPacketInfo.getId();
        this.liveId = redPacketInfo.getLiveId();
        this.time=redPacketInfo.getDuration();
        removeRedPacketDelayDestroy();
        removeRedPacketAnim();
        //发送延迟时间 防止短线或者丢包问题
        redPacketDelayDestroyunnable = new RedPacketDelayDestroyRunnable();
        //展示动画
        int isStart = redPacketInfo.getCurrentTime() - redPacketInfo.getStartTime();
        viewGroup = (ViewGroup) context.getWindow().getDecorView().getRootView();
        if (isStart>3000){
            //直接显示红包雨
            redPacketRun(getRedPacketDate(time));
            handler.postDelayed(redPacketDelayDestroyunnable,(time)*1000);
        }else if (isStart>2000){
            createStartAnimationView(context);
            mRedPacketAnimView.getTime().setText(String.valueOf(1));
            handler.postDelayed(redPacketDelayDestroyunnable,(time+1)*1000);
            showAnim();
        }else if (isStart>1000){
            createStartAnimationView(context);
            mRedPacketAnimView.getTime().setText(String.valueOf(2));
            handler.postDelayed(redPacketDelayDestroyunnable,(time+2)*1000);
            showAnim();
        }else{
            createStartAnimationView(context);
            mRedPacketAnimView.getTime().setText(String.valueOf(3));
            handler.postDelayed(redPacketDelayDestroyunnable,(time+3)*1000);
            showAnim();
        }
        return true;
    }
    /**
     * 结束红包雨.
     * @param isCallBack 是否需要回调结束
     */
    public void endGiftRain(boolean isCallBack) {
        removeRedPacketAnim();
        removeRedPacketDelayDestroy();
        if (mRedPacketRender != null) {
            mRedPacketRender.halt(isCallBack);
        }
    }
    //获取红包雨列表 根据时间整理的假数据 用于计算坐标
    private List<BoxInfo> getRedPacketDate(int time){
        List<BoxInfo> boxInfoList = new ArrayList<>();
        for (int i = 0; i < time * 10; i++) {
            BoxInfo boxInfo = new BoxInfo();
            boxInfoList.add(boxInfo);
        }
        return boxInfoList;
    }
    //创建开始的动画view
    private void createStartAnimationView(Activity context){
        mRedPacketAnimView = new RedPacketAnimView(context);
        viewGroup.addView(mRedPacketAnimView,viewGroup.getChildCount());
    }
    //展示开始动画
    private void showAnim(){
        mRedPacketAnimView.getImageView().setBackgroundResource(R.drawable.red_packet_start_anim);
        AnimationDrawable animationDrawable = (AnimationDrawable) mRedPacketAnimView.getImageView().getBackground();
        animationDrawable.start();

        if (redPacketAnimRunnable!=null){
            handler.removeCallbacks(redPacketAnimRunnable);
            redPacketAnimRunnable = null;

        }
        redPacketAnimRunnable = new RedPacketAnimRunnable();
        handler.postDelayed(redPacketAnimRunnable,1000);
    }

    //开始绘制红包雨
    private void redPacketRun(@NonNull List<BoxInfo> boxInfoList) {
        if (mRedPacketAnimView !=null){
            viewGroup.removeView(mRedPacketAnimView);
        }
        mRedPacketView = new TextureView(context);
        mRedPacketView.setOnTouchListener(onTouchListener);
        mRedPacketView.setOpaque(false); //设置textureview透明，这样底下还可以显示其他组件。
        viewGroup.addView(mRedPacketView,viewGroup.getChildCount());
        mRedPacketRender = new RedPacketRender(context.getResources(), boxInfoList, context);
        mRedPacketRender.setOnStateChangeListener(onStateChangeListener);
        mRedPacketView.setSurfaceTextureListener(mRedPacketRender);
        mRedPacketRender.start();
    }

    //打开的红包 用户用户统计以及上报接口回调使用
    private synchronized void openGift(BoxInfo boxInfo) {
        if (mRedPacketView == null || mRedPacketRender == null) {
            return;
        }
        if (mRedPacketStateListener != null) {
            mRedPacketStateListener.openRedPacket(redPacketId,liveId);
        }
    }

    //移除红包雨销毁的延迟消息
    private void removeRedPacketDelayDestroy(){
        if (redPacketDelayDestroyunnable !=null){
            handler.removeCallbacks(redPacketDelayDestroyunnable);
            redPacketDelayDestroyunnable = null;
        }
    }
    //移除开始动画的延迟消息
    private void removeRedPacketAnim(){
        if (redPacketAnimRunnable !=null){
            handler.removeCallbacks(redPacketAnimRunnable);
            redPacketAnimRunnable = null;
        }
    }
    public class RedPacketDelayDestroyRunnable implements Runnable{
        @Override
        public void run() {
            endGiftRain(true);
        }
    }
    public class RedPacketAnimRunnable implements Runnable{
        @Override
        public void run() {
            if (mRedPacketAnimView!=null){
                Integer integer = Integer.valueOf(mRedPacketAnimView.getTime().getText().toString());
                integer--;
                if (integer>=1){
                    mRedPacketAnimView.getTime().setText(String.valueOf(integer));
                    redPacketAnimRunnable = new RedPacketAnimRunnable();
                    handler.postDelayed(redPacketAnimRunnable,1000);
                }else{
                    List<BoxInfo> redPacketDate = getRedPacketDate(time);
                    //绘制红包雨
                    if (isRuning()){
                        redPacketRun(redPacketDate);
                    }
                }
            }
        }
    }
}
