package com.bokecc.livemodule.view.gift;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.bokecc.gift.pojo.Gift;
import com.bokecc.dwlivedemo.R;
import com.bokecc.livemodule.utils.ImageLoader;
import com.bokecc.livemodule.view.gift.interfaces.IGiftAnim;
import com.bokecc.livemodule.view.gift.interfaces.IGiftController;
import com.bokecc.sdk.mobile.live.common.log.ELog;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Muyangmin
 * @since 1.0.0
 */
public class GiftAnimView extends RelativeLayout implements IGiftAnim {
    //进入动画
    private Animation animWholeIn;
    //礼物图片动画
    private Animation animGiftPicIn;
    //数字动画
    private Animation animCombo;
    //礼物退出动画
    private Animation animWholeOut;
    //是否可追加
    private boolean canJoin;
    //是否可用
    private boolean available = true;
    /**
     * 这个是需要到达的总Combo数。
     */
    private AtomicInteger totalCombo = new AtomicInteger();
    protected TextView tvNickname, tvDetail,tvGiftNum;
    protected ImageView ivAnimHead, ivAnimGiftImg;
    protected Animation currentAnim;
    private IGiftController iGiftController;
    //是否展示联系数字
    private boolean isShownum;
    //当前的数字
    private AtomicInteger currentCombo = new AtomicInteger();
    //当前的礼物
    private Gift gift;
    //线程池
    private ScheduledThreadPoolExecutor scheduled;
    private AnimListenerAdapter animInListener = new AnimListenerAdapter("animWholeIn") {
        @Override
        public void onAnimationStart(Animation animation) {
            super.onAnimationStart(animation);
            setVisibility(VISIBLE);
            tvGiftNum.setVisibility(GONE);
            ivAnimGiftImg.setVisibility(GONE);
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            super.onAnimationEnd(animation);
            startAnimWrapper(ivAnimGiftImg, animGiftPicIn);
        }
    };
    private AnimListenerAdapter animPicInListener = new AnimListenerAdapter("animGiftPicIn") {

        @Override
        public void onAnimationStart(Animation animation) {
            super.onAnimationStart(animation);
            ivAnimGiftImg.setVisibility(VISIBLE);
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            super.onAnimationEnd(animation);
            if (isShownum){
                //如果需要展示连续数字动话的话再开启定时器
                startComboAnimation();
            }else{
                removeUIRunnable();
                uiRunnable = new UIRunnable(gift.getGiftNum());
                handler.post(uiRunnable);
            }
        }
    };
    private AnimListenerAdapter comBoListener = new AnimListenerAdapter("animCombo") {
        @Override
        public void onAnimationEnd(Animation animation) {
            super.onAnimationEnd(animation);
            //DO nothing; finish this on countdown timer.
            if (!isShownum){
                tvGiftNum.setText("X"+gift.getGiftNum());
                tvGiftNum.setVisibility(VISIBLE);
                startAnimWrapper(animWholeOut);
            }
        }
    };
    private AnimListenerAdapter animOutListener = new AnimListenerAdapter("animWholeOut") {
        @Override
        public void onAnimationEnd(Animation animation) {
            super.onAnimationEnd(animation);
            releaseRunnable();
            //这里为了保险 再次释放一次
            releaseThreadPool();
            reduction();
            //通知Controller
            if (iGiftController != null) {
                iGiftController.onPlayerAvailable(GiftAnimView.this);
            }

        }
    };
    public GiftAnimView(Context context) {
        super(context);
        init(context);
    }

    public GiftAnimView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public GiftAnimView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @SuppressWarnings("unused")
    public GiftAnimView(Context context, AttributeSet attrs, int defStyleAttr, int
            defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    protected void init(final Context context) {
        View view = LayoutInflater.from(context).inflate(getLayout(), this);
        ivAnimHead = (ImageView) findViewById(R.id.gift_anim_head);
        tvNickname = (TextView) findViewById(R.id.gift_anim_nikename);
        tvDetail = (TextView) findViewById(R.id.gift_anim_detail);
        ivAnimGiftImg = (ImageView) findViewById(R.id.gift_anim_img);
        tvGiftNum = (TextView) view.findViewById(R.id.gift_anim_num);
    }

    public int getLayout(){
        return R.layout.layout_gift_anim_view;
    }

    public void setiGiftController(IGiftController iGiftController) {
        this.iGiftController = iGiftController;
    }

    private void startComboAnimation() {
        ELog.e("GiftAnimView","startComboAnimation");
        scheduled = new ScheduledThreadPoolExecutor(2);
        scheduled.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                ELog.e("GiftAnimView","定时器");
                if (currentCombo.get() >=0 && currentCombo.get() < totalCombo.get()){
                    currentCombo.set((currentCombo.get()+1));
                    removeUIRunnable();
                    uiRunnable = new UIRunnable(currentCombo.get());
                    handler.post(uiRunnable);
                }else{
                    removeOutRunnable();
                    outRunnable = new OutRunnable();
                    handler.post(outRunnable);
                    releaseThreadPool();
                }
            }
        }, 1, 200, TimeUnit.MILLISECONDS);//0表示首次执行任务的延迟时间，40表示每次执行任务的间隔时间，TimeUnit.MILLISECONDS执行的时间间隔数值单位
    }

    @Override
    public boolean canJoin(Gift action) {
        //如果当前为空闲状态则currentAction为空，此时不应该走join流程，而是新的动画。
        if (gift==null){
            return false;
        }
        if (action == null){
            return false;
        }
        boolean fromSameUser = gift.getFromUserId().equals(action.getFromUserId());
        boolean isSameGift = gift.getGiftName().equals(action.getGiftName());
        return isShownum&&canJoin && fromSameUser && isSameGift;
    }

    @Override
    public boolean available() {
        return available && (!isShown());
    }

    @Override
    public void startAnim(Gift gift) {
        ELog.e("GiftAnimView","startAnim"+hashCode());
        //开始动画，设置忙碌标记
        available = false;
        canJoin = true;
        this.gift = gift;
        totalCombo.set(gift.getGiftNum());
        //完成数据显示
        Context context = getContext();
        tvDetail.setText(context.getString(R.string.room_gift_description, gift.getGiftName()));
        if (!TextUtils.isEmpty(gift.getFromUserName())){
            tvNickname.setText(gift.getFromUserName());
        }
        if (ivAnimHead.getVisibility()==VISIBLE){
            if (!TextUtils.isEmpty(gift.getFromUserAvatar())){
                ImageLoader.loadCircleBitmapIntoImageView(getContext(),gift.getFromUserAvatar(),ivAnimHead);
            }else{
                ivAnimHead.setImageResource(R.drawable.user_head_icon);
            }
        }

        if (!TextUtils.isEmpty(gift.getGiftImg())){
            ImageLoader.loadGifIntoImageView(getContext().getApplicationContext(),gift.getGiftImg(),ivAnimGiftImg);
        }
        //初始化动画
        animWholeIn = AnimationUtils.loadAnimation(context, R.anim.local_gift_whole_in);
        //This is not a copy error
        animGiftPicIn = AnimationUtils.loadAnimation(context, R.anim.local_gift_pic_in);
        animCombo = AnimationUtils.loadAnimation(context, R.anim.local_gift_combo);
        animWholeOut = AnimationUtils.loadAnimation(context, R.anim.local_gift_whole_out);
        animWholeIn.setAnimationListener(animInListener);
        animGiftPicIn.setAnimationListener(animPicInListener);
        animCombo.setAnimationListener(comBoListener);
        animWholeOut.setAnimationListener(animOutListener);
        animWholeOut.setDuration(getAnimWholeOutDuring());
        //第一个动画，播放整体View从左到右的淡入位移效果。
        startAnimWrapper(animWholeIn);
    }

    public long getAnimWholeOutDuring(){
        return animWholeOut.getDuration();
    }


    @Override
    public synchronized void joinAnim(Gift action) {
        //目前无需更新currentAction，因为始终都是同一种类型的
        totalCombo.set(totalCombo.get()+action.getGiftNum());
    }

    private void startAnimWrapper(Animation animation){
        startAnimWrapper(this, animation);
    }

    private void startAnimWrapper(View view, Animation animation){
        view.startAnimation(animation);
        currentAnim = animation;
    }

    @Override
    public void cancelAnim() {
        ELog.e("GiftAnimView","cancelanim");
        if (currentAnim!=null && currentAnim.isInitialized()){
            currentAnim.cancel();
        }
        //防止页面销毁该页面还在加载数据
//        Glide.with(getContext().getApplicationContext()).pauseRequests();
        releaseRunnable();
        releaseThreadPool();
        reduction();
    }
    private void reduction(){
        //设置下个动画可加入
        available = true;
        //已经结束，设置同类动画不可Join
        canJoin = false;
        //重置TotalCombo
        totalCombo.set(0);
        //重置文字，消除下次显示时的残留
        tvGiftNum.setText("X1");
        //设置为不可见状态
        setVisibility(INVISIBLE);
        ivAnimGiftImg.setVisibility(INVISIBLE);
        tvGiftNum.setText("");
        currentCombo.set(0);
    }
    private void releaseRunnable(){
        removeOutRunnable();
        removeUIRunnable();
    }
    private void releaseThreadPool(){
        try{
            if (scheduled!=null){
                if (!scheduled.isShutdown()){
                    scheduled.shutdownNow();
                }
                scheduled = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void setShowHead(boolean isShowHead) {
        if (isShowHead){
            ivAnimHead.setVisibility(VISIBLE);
        }else{
            ivAnimHead.setVisibility(GONE);
        }
    }

    public void setShowNum(boolean isShownum) {
        this.isShownum = isShownum;
    }

    private class AnimListenerAdapter implements Animation.AnimationListener {

        private String animTag;

        public AnimListenerAdapter(String animTag) {
            this.animTag = animTag;
        }

        @Override
        public void onAnimationStart(Animation animation) {
            logIfDebug("onAnimationStart");
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            logIfDebug("onAnimationEnd");
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            logIfDebug("onAnimationRepeat");
        }

        private void logIfDebug(String msg) {
            ELog.v("GiftAnimView", " %s: "+animTag+"----- %s -----"+ msg+"   "+GiftAnimView.this.hashCode());
        }
    }

    private UIRunnable uiRunnable;
    private OutRunnable outRunnable;
    private Handler handler = new Handler(Looper.getMainLooper());
    private void removeUIRunnable(){
        if (uiRunnable!=null){
            handler.removeCallbacks(uiRunnable);
            uiRunnable = null;
        }
    }
    private void removeOutRunnable(){
        if (outRunnable!=null){
            handler.removeCallbacks(outRunnable);
            outRunnable = null;
        }
    }
    private class UIRunnable implements Runnable{
        private int num;

        public UIRunnable(int num){
            this.num = num;
        }
        @Override
        public void run() {
            ELog.e("GiftAnimView","UIRunnable");
            startAnimWrapper(tvGiftNum, animCombo);
        }
    }
    private class OutRunnable implements Runnable{
        @Override
        public void run() {
            ELog.e("GiftAnimView","OutRunnable");
            startAnimWrapper(animWholeOut);
        }
    }
}
