package com.wisewoods.eduandroid.ui;


import static com.tencent.liteav.meeting.ui.CreateMeetingActivity.VIDEO_QUALITY_HD;
import static com.tencent.trtc.TRTCCloudDef.TRTC_AUDIO_QUALITY_SPEECH;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.Utils;
import com.tencent.liteav.live.model.TRTCMeeting;
import com.tencent.liteav.live.ui.MeetingMainActivity;
import com.tencent.liteav.live.ui.utils.StateBarUtils;
import com.wisewoods.base.app.UserManager;
import com.wisewoods.base.base.BaseActivity;
import com.wisewoods.base.bean.BaseEvent;
import com.wisewoods.base.bean.Results;
import com.wisewoods.base.net.JDCallback;
import com.wisewoods.base.net.LogicException;
import com.wisewoods.base.utils.$;
import com.wisewoods.base.utils.DialogUtils;
import com.wisewoods.eduandroid.app.App;
import com.wisewoods.eduandroid.databinding.ActivityShowLiveBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import retrofit2.Call;
import retrofit2.Response;

public class ShowLiveActivity extends BaseActivity<ActivityShowLiveBinding> {

    private TRTCMeeting trtcMeeting;
    private boolean isFront = true;
    private String id;
    private String roomId;
    private int liveStatus;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void end(BaseEvent.EndLiveEvent endLiveEvent) {
        finish();
    }

    public static void start(String id, String roomId, int liveStatus) {
        Intent intent = new Intent(ActivityUtils.getTopActivity(), ShowLiveActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("roomId", roomId);
        intent.putExtra("liveStatus", liveStatus);
        ActivityUtils.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startPreview();
    }

    @Override
    protected void onPause() {
        super.onPause();
        trtcMeeting.stopCameraPreview();
    }

    @Override
    protected boolean hasEvent() {
        return true;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        StateBarUtils.setDarkStatusBar(this);
        id = getIntent().getStringExtra("id");
        roomId = getIntent().getStringExtra("roomId");
        liveStatus = getIntent().getIntExtra("liveStatus", 0);
        trtcMeeting = TRTCMeeting.sharedInstance(Utils.getApp());

        initUI();

        binding.btnSwitchCamera.setOnClickListener(v -> {
            if (trtcMeeting != null) {
                isFront = !isFront;
                trtcMeeting.switchCamera(isFront);
            }
        });
        binding.btnStartRoom.setOnClickListener(v -> {
            if (liveStatus == 0) {
                startLive();
            } else {
                enterRoom(false);
            }
        });
        binding.btnEndRoom.setOnClickListener(v -> {
            endLive();
        });
        binding.btnCloseBeforeLive.setOnClickListener(v -> finish());
    }

    private void initUI() {
        if (liveStatus == 0) {
            binding.btnStartRoom.setText("开始直播");
            binding.flEnd.setVisibility(View.GONE);
        } else {
            binding.btnStartRoom.setText("进入直播");
            binding.flEnd.setVisibility(View.VISIBLE);
        }
    }

    private void endLive() {
        DialogUtils.showCommon(
                "确认结束直播?", (DialogUtils.IDialogOnOKListener) dialog -> {
                    App.api.updateLiveStartEnd(roomId, 2)
                            .enqueue(new JDCallback<Results>() {
                                @Override
                                public void onS(Response<Results> response, Results results) {
                                    $.toast("结束直播");
                                    EventBus.getDefault().post(new BaseEvent.EndLiveEvent());
                                    EventBus.getDefault().post(new BaseEvent.LiveRrefreshEvent());
                                }

                                @Override
                                public void onFailure(Call<Results> call, Throwable t) {
                                    if (t instanceof LogicException) {
                                        int code = ((LogicException) t).code;
                                        if (code == -3) {
                                            $.toast("结束直播");
                                            EventBus.getDefault().post(new BaseEvent.EndLiveEvent());
                                            EventBus.getDefault().post(new BaseEvent.LiveRrefreshEvent());
                                        } else {
                                            super.onFailure(call, t);
                                        }
                                    }
                                }
                            });
                });

    }

    private void startLive() {
        DialogUtils.showCommon(
                "确认开始直播?", (DialogUtils.IDialogOnOKListener) dialog -> {
                    App.api.updateLiveStartEnd(roomId, 1)
                            .enqueue(new JDCallback<Results>() {
                                @Override
                                public void onS(Response<Results> response, Results results) {
                                    liveStatus = 1;
                                    initUI();
                                    EventBus.getDefault().post(new BaseEvent.LiveRrefreshEvent());
                                    enterRoom(true);
                                }

                                @Override
                                public void onFailure(Call<Results> call, Throwable t) {
                                    if (t instanceof LogicException) {
                                        int code = ((LogicException) t).code;
                                        if (code == -4) {
                                            liveStatus = 1;
                                            initUI();
                                            EventBus.getDefault().post(new BaseEvent.LiveRrefreshEvent());
                                            enterRoom(false);
                                        } else {
                                            super.onFailure(call, t);
                                        }
                                    }
                                }
                            });
                });
    }

    private void enterRoom(boolean b) {
        String userId = UserManager.getUid();
        String userAvatar = UserManager.getAvatar();
        String userName = TextUtils.isEmpty(UserManager.getUser().nickName) ? UserManager.getUser().userName
                : UserManager.getUser().nickName;
        MeetingMainActivity.enterRoom(activity,
                roomId,
                userId,
                userName,
                userAvatar,
                b,
                b,
                TRTC_AUDIO_QUALITY_SPEECH,
                VIDEO_QUALITY_HD,
                isFront,
                false
        );
    }

    protected void startPreview() {
        // 打开本地预览，传入预览的 View
        binding.videoViewAnchor.setVisibility(View.VISIBLE);
        $.requestLive(this, () -> {
            trtcMeeting.startCameraPreview(isFront, binding.videoViewAnchor);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        trtcMeeting.stopCameraPreview();
    }
}
