package com.duben.microtribe.video.tx.newrecommend;

import static com.duben.microtribe.mvp.model.Vedio3dosKt.VEDIO3DOS_FREE;
import static com.duben.microtribe.mvp.model.VideoMultiItemEntityKt.MULTI_ITEM_1;
import static com.duben.microtribe.mvp.model.VideoMultiItemEntityKt.MULTI_ITEM_2;
import static com.duben.microtribe.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.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.duben.microtribe.R;
import com.duben.microtribe.mvp.model.VedioBean;
import com.duben.microtribe.mvp.model.VideoMultiItemEntity4;
import com.duben.microtribe.video.tx.PlayerManager;
import com.duben.microtribe.video.tx.TXVideoBaseView;
import com.duben.microtribe.video.tx.TXVodPlayerWrapper;
import com.duben.microtribe.video.tx.VideoModel;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class NewSuperShortVideoView extends RelativeLayout {

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

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

    private int mCurrentPosition = 0;

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

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

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

    public void loadData(VedioBean vedioBean, List<VideoMultiItemEntity4> list, int currentPosition) {
        mLastPositionInIDLE = -1;
        this.mCurrentPosition = currentPosition;
        mAdapter.setVedioBean(vedioBean);
        mAdapter.setNewInstance(list);

        onItemClick(mCurrentPosition);
    }

    public void updateData(int currentPosition) {
        this.mCurrentPosition = currentPosition;

        VideoMultiItemEntity4 videoMultiItemEntity4 = getData().get(currentPosition);
        videoMultiItemEntity4.setItemType(MULTI_ITEM_1);
        videoMultiItemEntity4.setType(VEDIO3DOS_FREE);
        mAdapter.setData(currentPosition, videoMultiItemEntity4);

        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 NewTxVideoAdapter();
        mAdapter.setNewInstance(new ArrayList<>());
        mAdapter.setOnVideoEndListener(() -> onItemClick(mCurrentPosition + 1, true));
        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(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (!recyclerView.canScrollVertically(1) || !recyclerView.canScrollVertically(-1)) {
                    onScrollStateChanged(recyclerView, RecyclerView.SCROLL_STATE_IDLE);
                }
            }

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://停止滚动

                        View view = mSnapHelper.findSnapView(mLayoutManager);
                        int position = recyclerView.getChildAdapterPosition(view);
                        if (position == mCurrentPosition || position == RecyclerView.NO_POSITION)
                            return;
                        Log.i(TAG, "[SCROLL_STATE_IDLE] mLastPositionInIDLE " + mLastPositionInIDLE + " position " + position);

                        mCurrentPosition = 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 >= getData().size() || getData().get(position).getItemType() != MULTI_ITEM_1)
            return;

        if (position == getData().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(getData().get(position).getVideoModel());
            if (txVodPlayerWrapper != null && mBaseItemView != null) {
                Log.i(TAG, "txVodPlayerWrapper " + txVodPlayerWrapper + "url-- " + getData().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 (VideoMultiItemEntity4 videoMultiItemEntity : getData()) {
            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) {
        onItemClick(position, false);
    }

    public void onItemClick(final int position, boolean isVideoEnd) {
        if (getData() == null || position >= getData().size()) return;

        if (isVideoEnd) {
            changeLayoutPosition(position);
            // 执行 onScrollListener
            mRecyclerView.smoothScrollToPosition(position);
        } else {
            mRecyclerView.scrollToPosition(position);
            mRecyclerView.post(() -> {
                Log.i(TAG, "onItemClick");
                mCurrentPosition = position;

                onPageSelectedMethod(position);
            });
        }
    }

    private void changeLayoutPosition(int position) {
        try {
            Class<LinearLayoutManager> lm = LinearLayoutManager.class;
            Field mPendingScrollPosition = lm.getDeclaredField("mPendingScrollPosition");
            mPendingScrollPosition.setAccessible(true);
            mPendingScrollPosition.set(mLayoutManager, position);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public List<VideoMultiItemEntity4> getData() {
        return mAdapter.getData();
    }

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

    public int getCurrentPosition() {
        return mCurrentPosition;
    }

    public void setOnCustomChildClickListener(NewTxVideoAdapter.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 (getData() != null && getData().size() > 0 && position < getData().size()) {
            return getData().get(position).getItemType() == MULTI_ITEM_3;
        }
        return false;
    }

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