package com.dlc.exam.ui.learn;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.dlc.exam.common.CommonUtils;
import com.dlc.exam.databinding.ActivityLearnDetailExoBinding;
import com.dlc.exam.ui.common.BaseCountDownActivity;
import com.dlc.exam.ui.learn.test.ClassTestActivity;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.Player;
import com.google.gson.Gson;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.client.ApiRepository;
import com.rc.httpcore.vo.request.ExamLearnReq;

import io.reactivex.disposables.Disposable;

public class LearnDetailExoActivity extends BaseCountDownActivity<ActivityLearnDetailExoBinding> implements View.OnClickListener {
    private ActivityLearnDetailExoBinding binding;
    private ExoPlayer exoPlayer;
    private long learnTimeSecond = 0L;
    private LearnChapterBean learnChapterBean;
    private boolean learnCompleted = false;// 是否已完成学习

    @NonNull
    @Override
    protected ActivityLearnDetailExoBinding createViewBinding() {
        return ActivityLearnDetailExoBinding.inflate(LayoutInflater.from(this));
    }

    @Override
    protected void initViews(@Nullable Bundle savedInstanceState) {
        super.initViews(savedInstanceState);
        binding = getViewBinding();
        Intent getIntent = getIntent();
        if (null != getIntent && getIntent.hasExtra("Chapter")) {
            learnChapterBean = getIntent.getParcelableExtra("Chapter");
            LogUtils.json(learnChapterBean);
            boolean relearn = getIntent.getBooleanExtra("relearn", false);
            if (null == learnChapterBean) {
                finish();
                return;
            }
            binding.back.setOnClickListener(this);
            binding.titleText.setText(learnChapterBean.title);
            // 是否完成学习
            binding.learnCompleted.setVisibility(relearn ? View.GONE : View.VISIBLE);
            binding.learnCompleted.setOnClickListener(this);
            // 直接播放
            initExo();
        } else {
            finish();
        }
    }

    private Handler cdHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            learnTimeSecond++;
            binding.learnDuration.setText("已学习时长:" + CommonUtils.INSTANCE.formatLearnTime(learnTimeSecond));
            sendEmptyMessageDelayed(1, 1000);
            if (learnTimeSecond >= learnChapterBean.duration) {
                binding.learnCompleted.setEnabled(true);
            }
        }
    };

    /**
     * 播放视频
     */
    private void initExo() {
        String url = learnChapterBean.chapterData;
        if (!url.startsWith("http")) {
            url = HttpConfig.Companion.getAPI_BASE_URL() + url;
        }
        LogUtils.d("Jayce", url);
//        url = "https://media.wxzxzj.com/the_garden_of_words_trailer_english__1080p.m3u8";
        exoPlayer = new ExoPlayer.Builder(this).build();
        exoPlayer.addListener(new Player.Listener() {
            /**
             * 播放状态改变
             * @param playbackState The new playback {@link Player.State state}.
             */
            @Override
            public void onPlaybackStateChanged(int playbackState) {
                Player.Listener.super.onPlaybackStateChanged(playbackState);
                //  播放
                if (playbackState == Player.STATE_READY && exoPlayer.getPlayWhenReady()) {
                    // 开始学习
                    startLearn();
                }
            }

            /**
             * 播放出错
             * @param error The error.
             */
            @Override
            public void onPlayerError(PlaybackException error) {
                Player.Listener.super.onPlayerError(error);
                binding.errTV.setText("播放异常:" + error.errorCode + "," + error.getMessage());
                Log.e("Jayce", error.errorCode + "," + error.getMessage());
            }
        });
        MediaItem mediaItem = MediaItem.fromUri(url);
        exoPlayer.setMediaItem(mediaItem);
        binding.styledPlayerView.setUseController(false);
        binding.styledPlayerView.setPlayer(exoPlayer);
        exoPlayer.prepare();
        exoPlayer.play();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (exoPlayer != null) {
            exoPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (exoPlayer != null) {
            exoPlayer.play();
        }
    }

    @Override
    protected void onDestroy() {
        cdHandler.removeMessages(1);
        cdHandler.removeCallbacksAndMessages(null);
        cdHandler = null;
        super.onDestroy();
        if (exoPlayer != null) {
            exoPlayer.release();
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == binding.back.getId()) {
            onBackPressed();
        }
        // 完成学习
        else if (v.getId() == binding.learnCompleted.getId()) {
            learnTimeSecond = 0L;
            cdHandler.removeMessages(1);
            finishLearn();
        }
    }

    /**
     * 完成学习
     */
    private void finishLearn() {
        showLoading("保存中...", false);
        ExamLearnReq examLearnReq = new ExamLearnReq();
        examLearnReq.chapterId = learnChapterBean.chapterId;
        examLearnReq.courseId = learnChapterBean.courseId;
        Log.d("Jayce", "完成学习:" + new Gson().toJson(examLearnReq));
        Disposable disposable = ApiRepository.INSTANCE.examLearnFinish(examLearnReq).subscribe(learnBonusBean -> {
            dismissLoading();
            Log.d("Jayce", new Gson().toJson(learnBonusBean));
            learnCompleted = true;
            new LearnCompletedDialog(LearnDetailExoActivity.this, learnBonusBean, false, learnChapterBean.assessStatus, () -> {
                binding.learnCompleted.setEnabled(false);
                // 课后考核
                if (learnChapterBean.assessStatus) {
                    Intent intent = new Intent(LearnDetailExoActivity.this, ClassTestActivity.class);
                    intent.putExtra("chapterId", learnChapterBean.chapterId);
                    startActivity(intent);
                    setResult(RESULT_OK);
                }
                finish();
                return null;
            }).show();
        }, throwable -> {
            dismissLoading();
            throwable.printStackTrace();
            showNetError(throwable);
        });
        addDisposable(disposable);
    }

    /**
     * 开始学习
     */
    private void startLearn() {
        showLoading("加载中...", false);
        ExamLearnReq examLearnReq = new ExamLearnReq();
        examLearnReq.chapterId = learnChapterBean.chapterId;
        examLearnReq.courseId = learnChapterBean.courseId;
        Log.d("Jayce", "开始学习:" + new Gson().toJson(examLearnReq));
        Disposable disposable = ApiRepository.INSTANCE.examLearnStart(examLearnReq).subscribe(aBoolean -> {
            dismissLoading();
            learnTimeSecond = 0L;
            cdHandler.sendEmptyMessage(1);

        }, throwable -> {
            dismissLoading();
            throwable.printStackTrace();
            showNetError(throwable);
        });
        addDisposable(disposable);
    }

    @Override
    public void onBackPressed() {
        if (learnCompleted) {
            setResult(RESULT_OK);
        }
        super.onBackPressed();
    }
}