package com.duben.happyplaylet.video.tx;

import static com.duben.happyplaylet.mvp.model.VideoMultiItemEntityKt.MULTI_ITEM_1;
import static com.duben.happyplaylet.mvp.model.VideoMultiItemEntityKt.MULTI_ITEM_2;
import static com.duben.happyplaylet.mvp.model.VideoMultiItemEntityKt.MULTI_ITEM_3;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.duben.happyplaylet.R;
import com.duben.happyplaylet.ad.draw.DrawExpressManager;
import com.duben.happyplaylet.manager.UserManager;
import com.duben.happyplaylet.mvp.model.VedioBean;
import com.duben.happyplaylet.mvp.model.VideoMultiItemEntity;
import com.duben.happyplaylet.video.tx.adapter.TxVideoAdapter;

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

public class SuperShortVideoView extends RelativeLayout {

    private static final String TAG = "SuperShortVideoView";
    private static final int MAX_PLAYER_COUNT_ON_PASS = 3;

    private RecyclerView mRecyclerView;
    private TxVideoAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private PagerSnapHelper mSnapHelper;
    private int mLastPositionInIDLE = -1;
    private TXVideoBaseView mBaseItemView;
    private boolean mIsOnDestroy;
    private PlayerManager mPlayerManager;

    private int mCurrentPosition = 0;

    private List<VideoMultiItemEntity> mList = new ArrayList<>();

    public SuperShortVideoView(Context context) {
        this(context, null);
    }

    public SuperShortVideoView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

    public void loadMoreData(List<VideoMultiItemEntity> list) {
        this.mList.clear();
        this.mList = list;
        mAdapter.setNewInstance(mList);

        onItemClick(mCurrentPosition);
    }

    public void loadData(VedioBean vedioBean, List<VideoMultiItemEntity> list, int currentPosition) {
        this.mList = list;
        this.mCurrentPosition = currentPosition;
        mAdapter.setVedioBean(vedioBean);
        mAdapter.setNewInstance(mList);

        onItemClick(mCurrentPosition);
    }

    public void init(Context context) {
        View mRootView = LayoutInflater.from(context).inflate(R.layout.super_short_video_view, null);
        addView(mRootView);
        mPlayerManager = new PlayerManager(getContext());
        mRecyclerView = mRootView.findViewById(R.id.rv_super_short_video);
        mSnapHelper = new PagerSnapHelper();
        mSnapHelper.attachToRecyclerView(mRecyclerView);
        mAdapter = new TxVideoAdapter();
        mAdapter.setNewInstance(mList);
        mAdapter.setOnVideoEndListener(() -> onItemClick(mCurrentPosition + 1));
        mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false) {
            @Override
            protected int getExtraLayoutSpace(RecyclerView.State state) {
                return 300;
            }
        };
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemViewCacheSize(6);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setDrawingCacheEnabled(true);
        mRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
        mRecyclerView.setAdapter(mAdapter);
        addListener();
    }

    private void addListener() {
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (!recyclerView.canScrollVertically(1) || !recyclerView.canScrollVertically(-1)) {
                    onScrollStateChanged(recyclerView, RecyclerView.SCROLL_STATE_IDLE);
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://停止滚动
                        View view = mSnapHelper.findSnapView(mLayoutManager);
                        int position = recyclerView.getChildAdapterPosition(view);
                        if (position == mCurrentPosition) return;
                        Log.i(TAG, "[SCROLL_STATE_IDLE] mLastPositionInIDLE " + mLastPositionInIDLE + " position " + position);
                        mCurrentPosition = position;
                        addAdView(position);

                        onPageSelectedMethod(position);

                        if (isLuckPosition(position)) {
                            mAdapter.notifyItemChanged(position);
                        }
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING://拖动
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动
                        break;
                }
            }
        });
    }

    private void onPageSelectedMethod(int position) {
        if (mOnPageChangeListener != null) mOnPageChangeListener.onPageChange(position);

        if (position >= mList.size() || this.mList.get(position).getItemType() != MULTI_ITEM_1)
            return;

        if (position == mList.size()) {
            if (mBaseItemView != null) {
                mLastPositionInIDLE = -1;
                mBaseItemView.stopForPlaying();
            }
            return;
        }

        if (mLastPositionInIDLE != position) {
            View view = mSnapHelper.findSnapView(mLayoutManager);
            if (view == null) {
                return;
            }
            mBaseItemView = view.findViewById(R.id.baseItemView);
            Log.i(TAG, "onPageSelected " + position);
            List<VideoModel> tempUrlList = initUrlList(position, MAX_PLAYER_COUNT_ON_PASS);
            mPlayerManager.updateManager(tempUrlList);
            TXVodPlayerWrapper txVodPlayerWrapper = mPlayerManager.getPlayer(mList.get(position).getVideoModel());
            if (txVodPlayerWrapper != null && mBaseItemView != null) {
                Log.i(TAG, "txVodPlayerWrapper " + txVodPlayerWrapper + "url-- " + mList.get(position).getVideoModel().videoURL);
                Log.i(TAG, "txVodPlayerWrapper " + txVodPlayerWrapper);
                mBaseItemView.setTXVodPlayer(txVodPlayerWrapper);
            }
            mLastPositionInIDLE = position;
        }
        if (mBaseItemView != null && !mIsOnDestroy) {
            mBaseItemView.startPlay();
        }
    }

    /**
     * 初始化向PlayManager传递的urlList
     *
     * @param startIndex 开始的索引
     * @param maxCount   传递的urlList的数目
     * @return
     */
    private List<VideoModel> initUrlList(int startIndex, int maxCount) {
        List<VideoModel> videoModels = new ArrayList<>();
        for (VideoMultiItemEntity videoMultiItemEntity : this.mList) {
            videoModels.add(videoMultiItemEntity.getVideoModel());
        }
        int i = startIndex - 1;
        if (i + maxCount > videoModels.size()) {
            i = videoModels.size() - maxCount;
        }
        if (i < 0) {
            i = 0;
        }
        int addedCount = 0;
        List<VideoModel> cacheList = new ArrayList<>();
        while (i < videoModels.size() && addedCount < maxCount) {
            cacheList.add(videoModels.get(i));
            addedCount++;
            i++;
        }
        return cacheList;
    }

    public void resume() {
        if (mBaseItemView != null && !isLuckPosition(mCurrentPosition) && !isAdPosition(mCurrentPosition)) {
            mBaseItemView.startPlay();
        }
    }

    public void pause() {
        if (mBaseItemView != null) {
            mBaseItemView.pausePlayer();
        }
    }

    public void releasePlayer() {
        if (mBaseItemView != null) {
            mBaseItemView.stopPlayer();
        }
        mPlayerManager.releasePlayer();
    }

    public void onItemClick(final int position) {
        if (position >= mList.size()) return;

        mRecyclerView.scrollToPosition(position);
        mRecyclerView.post(() -> {
            Log.i(TAG, "onItemClick");
            mCurrentPosition = position;

            addAdView(mCurrentPosition);
            onPageSelectedMethod(position);
        });
    }

    public List<VideoMultiItemEntity> getData() {
        return mList;
    }

    public int getRealSeeIndex() {
        if (mList != null && mList.size() > 0) {
            VideoMultiItemEntity videoMultiItemEntity = mList.get(mCurrentPosition);
            if (videoMultiItemEntity.getItemType() == MULTI_ITEM_1) {
                return videoMultiItemEntity.getVideo().getVedioIndex() - 1;
            }
        }
        return mCurrentPosition;
    }

    public int getCurrentPosition() {
        return mCurrentPosition;
    }

    public void setOnCustomChildClickListener(TxVideoAdapter.OnCustomChildClickListener onCustomChildClickListener) {
        mAdapter.setOnCustomChildClickListener(onCustomChildClickListener);
    }

    public void onDestroy() {
        mIsOnDestroy = true;
    }

    public interface OnPageChangeListener {
        void onPageChange(int position);
    }

    private OnPageChangeListener mOnPageChangeListener;

    public void setOnPageChangeListener(OnPageChangeListener onPageChangeListener) {
        this.mOnPageChangeListener = onPageChangeListener;
    }

    public boolean isAdPosition(int position) {
        if (mList != null && mList.size() > 0) {
            return mList.get(position).getItemType() == MULTI_ITEM_3;
        }
        return false;
    }

    public boolean isLuckPosition(int position) {
        if (mList != null && mList.size() > 0) {
            return mList.get(position).getItemType() == MULTI_ITEM_2;
        }
        return false;
    }

    private int lastAddAdPosition = 0;

    private void addAdView(int position) {
        // VIP 不展示
        if (UserManager.getInstance().getVipFlag()) return;
        // 每隔3个视频出现一个广告
        if (position + 1 < 2 || (position + 1) % 3 != 0 || lastAddAdPosition > position
                || isAdPosition(position) || isLuckPosition(position))
            return;

        int addAdPosition = position + 1;

        // 校验是否是最后一页
        if (addAdPosition >= mList.size()) {
            addAdPosition = position;
        }

        if (DrawExpressManager.Companion.getInstance().getAdIsLoadSuc()) {
            VideoMultiItemEntity itemAD = new VideoMultiItemEntity(MULTI_ITEM_3, null, new VideoModel(""));
            mList.add(addAdPosition, itemAD);
            mAdapter.notifyItemInserted(addAdPosition);
            lastAddAdPosition = addAdPosition;
        }
    }
}
