package com.duben.microtribe.video.tx;

import static com.duben.microtribe.mvp.model.VideoMultiItemEntityKt.MULTI_ITEM_1;
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 androidx.recyclerview.widget.SimpleItemAnimator;

import com.duben.microtribe.ad.draw.HomeDrawExpressManager;
import com.duben.microtribe.manager.UserManager;
import com.duben.microtribe.mvp.model.VideoMultiItemEntity2;
import com.duben.microtribe.video.tx.adapter.TxRecommendVideoAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.duben.microtribe.R;
import com.duben.microtribe.mvp.model.VedioBean;

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

public class RecommendVideoView extends RelativeLayout {

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

    private RecyclerView mRecyclerView;
    private SmartRefreshLayout mSmartRefreshLayout;
    private TxRecommendVideoAdapter 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<VideoMultiItemEntity2> mList = new ArrayList<>();

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

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

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

    public void loadData(List<VedioBean> list) {
        if (this.mList != null) {
            this.mList.clear();
        }

        this.mList = getAdapterData(list);
        mAdapter.setNewInstance(this.mList);
    }

    public void loadMoreData(List<VedioBean> list) {
        this.mList.addAll(getAdapterData(list));
        mAdapter.notifyItemRangeInserted(this.mList.size() - list.size(), list.size());
    }

    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);
        mSmartRefreshLayout = mRootView.findViewById(R.id.src_video);
        mSmartRefreshLayout.setEnableRefresh(false);
        mSnapHelper = new PagerSnapHelper();
        mSnapHelper.attachToRecyclerView(mRecyclerView);
        mAdapter = new TxRecommendVideoAdapter();
        mAdapter.setNewInstance(getAdapterData(null));
        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);
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        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);
                        Log.i(TAG, "[SCROLL_STATE_IDLE] mLastPositionInIDLE " + mLastPositionInIDLE + " position " + position);
                        mCurrentPosition = position;
                        onPageSelectedMethod(position);
                        mAdapter.setCurrentPosition(mCurrentPosition);

                        addAdView(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 (mList == null || position >= mList.size() || this.mList.get(position).getItemType() != MULTI_ITEM_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) {
                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 (VideoMultiItemEntity2 videoMultiItemEntity2 : this.mList) {
            videoModels.add(videoMultiItemEntity2.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) {
            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) {
        mRecyclerView.scrollToPosition(position);
        mRecyclerView.post(() -> {
            Log.i(TAG, "onItemClick");
            mCurrentPosition = position;
            onPageSelectedMethod(position);
        });
    }

    public int getCurrentPosition() {
        return mCurrentPosition;
    }

    public void onDestroy() {
        mIsOnDestroy = true;
    }

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

    private OnPageChangeListener mOnPageChangeListener;

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

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

    private TXVideoBaseView.OnVideoEndListener mOnVideoEndListener;

    public void setOnVideoEndListener(TXVideoBaseView.OnVideoEndListener onVideoEndListener) {
        mAdapter.setOnVideoEndListener(onVideoEndListener);
    }

    public void hideLoadMore() {
        mSmartRefreshLayout.finishLoadMore();
        mSmartRefreshLayout.postDelayed(() ->
                mRecyclerView.smoothScrollToPosition(mCurrentPosition), 200);
    }

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        mSmartRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
    }

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

    private List<VideoMultiItemEntity2> getAdapterData(List<VedioBean> list) {
        List<VideoMultiItemEntity2> data = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                VideoMultiItemEntity2 item = new VideoMultiItemEntity2(MULTI_ITEM_1, list.get(i),
                        new VideoModel(list.get(i).getRecommendUrl()));
                data.add(item);
            }
        }
        return data;
    }

    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) return;

        if (HomeDrawExpressManager.Companion.getInstance().getAdIsLoadSuc()) {
            VideoMultiItemEntity2 itemAD = new VideoMultiItemEntity2(MULTI_ITEM_3, null, new VideoModel(""));
            mList.add(position + 1, itemAD);
            mAdapter.notifyItemInserted(position + 1);
            lastAddAdPosition = position + 1;
        }
    }

}
