package com.hainaos.vc.activity.tiktok;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.hainaos.vc.CustomJzvd.JzvdStdAssert;
import com.hainaos.vc.R;
import com.hainaos.vc.adapter.TikTokRecyclerViewAdapter;
import com.hainaos.vc.base.mvvm.BaseMvvmActivity;
import com.hainaos.vc.bean.LocalVideoInfo;
import com.hainaos.vc.databinding.ActivityTiktokBinding;
import com.hainaos.vc.listener.OnViewPagerListener;
import com.hainaos.vc.utils.SPUtils;
import com.hainaos.vc.utils.ToastUtil;
import com.hainaos.vc.view.ViewPagerLayoutManager;

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

import cn.jzvd.Jzvd;

public class TikTokActivity extends BaseMvvmActivity<TikTokViewModel, ActivityTiktokBinding> {
    private static final String TAG = "TikTokActivity";

    private TikTokRecyclerViewAdapter mTikTokRecyclerViewAdapter;

    private int mCurrentPosition = -1;
    private int position = 0;
    private List<LocalVideoInfo> videoPath = new ArrayList<>();
    private int onGlobalLayout = -1;
    private int oldOrientation = 0;

    @Override
    public boolean setfitWindow() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_tiktok;
    }

    @Override
    protected void initDataBinding() {
        mViewModel.setCtx(this);
        mViewModel.setVDBinding(mViewDataBinding);
        mViewModel.setLifecycle(getLifecycleSubject());
//        mViewDataBinding.setClick(new BtnClick());
    }

    @Override
    protected void initView() {
        Configuration config = getResources().getConfiguration();
        oldOrientation = config.orientation;
        Log.e(TAG, "orientation first:" + oldOrientation);

        Intent intent = getIntent();
        if (null != intent) {
            position = intent.getIntExtra("position", 0);
            videoPath = intent.getParcelableArrayListExtra("list");
        }
        mTikTokRecyclerViewAdapter = new TikTokRecyclerViewAdapter(this, videoPath);
        mTikTokRecyclerViewAdapter.setVideoCompletListener(() -> {
            if (mCurrentPosition + 1 < videoPath.size()) {
                mViewDataBinding.rvTiktok.smoothScrollToPosition(mCurrentPosition + 1);
            } else {
                int singleLoop = (int) SPUtils.get(TikTokActivity.this, "loop", 0);
                if (singleLoop == 0) {
                    ToastUtil.show("播放完成");
                    finish();
                } else {
                    mViewDataBinding.rvTiktok.scrollToPosition(0);
                    mCurrentPosition = 0;
                    ToastUtil.show("列表结束，开始播放第一个视频");
                }
            }
        });
        mTikTokRecyclerViewAdapter.setOrientationChangeListener(new TikTokRecyclerViewAdapter.onOrientationChangeListener() {
            @Override
            public void onOrientationChange() {
                Configuration config = getResources().getConfiguration();
                Log.e(TAG, "orientation onOrientationChange:" + config.orientation);
            }
        });
        mTikTokRecyclerViewAdapter.setGotoFullScreenListener(new TikTokRecyclerViewAdapter.onGotoFullScreenListener() {
            @Override
            public void gotoFullScreen() {
                Configuration config = getResources().getConfiguration();
                oldOrientation = config.orientation;
                Log.e(TAG, "orientation gotoFullScreen:" + config.orientation);
            }
        });
        ViewPagerLayoutManager viewPagerLayoutManager = new ViewPagerLayoutManager(this, OrientationHelper.VERTICAL);
        mViewDataBinding.rvTiktok.setLayoutManager(viewPagerLayoutManager);
        mViewDataBinding.rvTiktok.setNestedScrollingEnabled(false);
        mViewDataBinding.rvTiktok.setAdapter(mTikTokRecyclerViewAdapter);
        mViewDataBinding.rvTiktok.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (onGlobalLayout == -1) {
                    mViewDataBinding.rvTiktok.scrollToPosition(position);
                    mCurrentPosition = position;
                    onGlobalLayout = 0;//只在第一次进行跳转
                }
            }
        });
        viewPagerLayoutManager.setOnViewPagerListener(new OnViewPagerListener() {
            @Override
            public void onInitComplete() {
                //自动播放第一条
                autoPlayVideo();
            }

            @Override
            public void onPageRelease(boolean isNext, int position) {
                if (mCurrentPosition == position) {
                    Jzvd.releaseAllVideos();
                }
            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                if (mCurrentPosition == position) {
                    return;
                }
                autoPlayVideo();
                mCurrentPosition = position;
            }
        });

        mViewDataBinding.rvTiktok.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {
                Jzvd jzvd = view.findViewById(R.id.videoplayer);
                if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource != null &&
                        jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                    if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                        Jzvd.releaseAllVideos();
                    }
                }
            }
        });

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Configuration config = getResources().getConfiguration();
        if (oldOrientation != config.orientation) {
            if (oldOrientation == Configuration.ORIENTATION_LANDSCAPE) {
                // 设为竖屏
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                oldOrientation = Configuration.ORIENTATION_LANDSCAPE;
            }
            // 如果当前是竖屏
            if (oldOrientation == Configuration.ORIENTATION_PORTRAIT) {
                // 设为横屏
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                oldOrientation = Configuration.ORIENTATION_PORTRAIT;
            }
        }
        Log.e(TAG, "orientation oldOrientation:" + config.orientation);

        Log.e(TAG, "orientation: " + config.orientation);
    }

    private void autoPlayVideo() {
        View child = mViewDataBinding.rvTiktok.getChildAt(0);
        if (child == null) {
            return;
        }
        JzvdStdAssert player = mViewDataBinding.rvTiktok.getChildAt(0).findViewById(R.id.videoplayer);
        if (player != null) {
            player.startVideoAfterPreloading();
        }
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mTikTokRecyclerViewAdapter) {
            mTikTokRecyclerViewAdapter = null;
        }
    }
}
