package xn.xxp.main.monitor;

import android.content.DialogInterface;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.GridLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.hikvision.hatomplayer.DefaultHatomPlayer;
import com.hikvision.hatomplayer.HatomPlayer;
import com.hikvision.hatomplayer.PlayCallback;
import com.hikvision.hatomplayer.PlayConfig;
import com.hikvision.hatomplayer.core.Quality;

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

import core.ui.activity.BaseCountDownActivity;
import core.util.FastClickDelegate;
import http.client.ApiRepository;
import http.vo.response.MonitorVo;
import io.reactivex.rxjava3.functions.Consumer;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import xn.xxp.app.LabApp;
import xn.xxp.databinding.ActivityMonitorBinding;
import xn.xxp.main.risk.VideoDialogFragment;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.LabConfig;
import xn.xxp.widget.ITitleBar;
import xn.xxp.widget.NavViewCompat;

public class MonitorActivity extends BaseCountDownActivity<ActivityMonitorBinding> {

    private ActivityMonitorBinding binding;
    private List<MonitorInfo> monitorInfoList = new ArrayList<>();
    private MonitorDialog monitorDialog;

    @Override
    public ITitleBar getMTitleBar() {
        return binding.titleBar;
    }

    @Override
    public NavViewCompat getMNavView() {
        return null;
    }

    @Override
    protected ActivityMonitorBinding createViewBinding() {
        return binding = ActivityMonitorBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        super.initViews(savedInstanceState);
        binding.navView.setNavListener(new NavViewCompat.NavListener() {
            @Override
            public void onHomeViewClicked() {
                logoutCountDownFinish();
            }

            @Override
            public void onBackViewClicked() {
                showLoading("正在退出...");
                ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Object>() {
                    @Override
                    public Object doInBackground() throws Throwable {
                        if (null != monitorInfoList) {
                            for (int i = 0; i < monitorInfoList.size(); i++) {
                                MonitorInfo monitorInfo = monitorInfoList.get(i);
                                HatomPlayer hatomPlayer = monitorInfo.getHatomPlayer();
                                if (null != hatomPlayer) {
                                    hatomPlayer.stop();
                                }
                            }
                        }
                        return null;
                    }

                    @Override
                    public void onSuccess(Object result) {
                        dismissLoading();
                        finish();
                    }
                });
            }

            @Override
            public void onFingerEnrollViewClicked() {

            }
        });


        LabConfig labConfig = RoomTool.getInstance().labConfigDao().getLabConfig();
        showLoading("加载中...");
        addDisposable(ApiRepository.INSTANCE.cameraBySubjectId(String.valueOf(labConfig.getLabId()), LabApp.userVo.userId, LabApp.userVo.userName, 3).subscribe(new Consumer<List<MonitorVo>>() {
            @Override
            public void accept(List<MonitorVo> monitorVos) throws Throwable {
                if (null != monitorVos && !monitorVos.isEmpty()) {
                    binding.gridLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            binding.gridLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            int width = binding.gridLayout.getWidth();
                            int height = binding.gridLayout.getHeight();

                            for (int i = 0; i < monitorVos.size(); i++) {
                                MonitorVo monitorVo = monitorVos.get(i);
                                MonitorInfo monitorInfo = new MonitorInfo();
                                TextureView textureView = new TextureView(MonitorActivity.this);
                                GridLayout.LayoutParams params = new GridLayout.LayoutParams();
                                params.width = width / 3;
                                params.height = height / 3;
                                params.setMargins(5, 5, 5, 5); // 设置间距
                                textureView.setLayoutParams(params);
                                textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
                                    @Override
                                    public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
                                        for (int j = 0; j < monitorInfoList.size(); j++) {
                                            MonitorInfo monitorInfo = monitorInfoList.get(j);
                                            SurfaceTexture surfaceTexture = monitorInfo.getTextureView().getSurfaceTexture();
                                            if (surfaceTexture == surface) {
                                                play(monitorInfo.getHatomPlayer(), surface, monitorInfo.getMonitorVo().streamUrl);
                                                break;
                                            }
                                        }
                                    }

                                    @Override
                                    public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

                                    }

                                    @Override
                                    public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
                                        return false;
                                    }

                                    @Override
                                    public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

                                    }
                                });

                                textureView.setOnClickListener(new FastClickDelegate(new Function1<View, Unit>() {
                                    @Override
                                    public Unit invoke(View view) {
                                        for (int j = 0; j < monitorInfoList.size(); j++) {
                                            MonitorInfo monitorInfo = monitorInfoList.get(j);
                                            if (monitorInfo.getTextureView() == view) {
                                                monitorDialog = new MonitorDialog(MonitorActivity.this, monitorInfo, new DialogInterface.OnDismissListener() {
                                                    @Override
                                                    public void onDismiss(DialogInterface dialog) {
                                                        dialog.dismiss();
                                                        monitorDialog = null;
                                                    }
                                                });
                                                monitorDialog.show();
                                                break;
                                            }
                                        }
                                        return null;
                                    }
                                }));

                                HatomPlayer hatomPlayer = new DefaultHatomPlayer();
                                PlayConfig playConfig = new PlayConfig();
                                playConfig.hardDecode = true;
                                playConfig.privateData = true;
                                hatomPlayer.setPlayConfig(playConfig);
                                hatomPlayer.setPlayStatusCallback(new PlayCallback.PlayStatusCallback() {
                                    @Override
                                    public void onPlayerStatus(@NonNull PlayCallback.Status status, String s) {
                                        LogUtils.d(status, s);
                                    }
                                });

                                monitorInfo.setTextureView(textureView);
                                monitorInfo.setMonitorVo(monitorVo);
                                monitorInfo.setHatomPlayer(hatomPlayer);

                                monitorInfoList.add(monitorInfo);

                                binding.gridLayout.addView(textureView);
                            }

                            dismissLoading();
                        }
                    });
                } else {
                    dismissLoading();
                    showToast("无监控信息!");
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Throwable {
                dismissLoading();
                LogUtils.e(Log.getStackTraceString(throwable));
            }
        }));
    }

    private void play(HatomPlayer hatomPlayer, SurfaceTexture surfaceTexture, String url) {
        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                hatomPlayer.setSurfaceTexture(surfaceTexture);
                hatomPlayer.setDataSource(url, null);
                hatomPlayer.changeStream(Quality.SUB_STREAM_LOW);
                hatomPlayer.start();
                return null;
            }

            @Override
            public void onSuccess(Object result) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("video_dialog");
        if (fragment instanceof VideoDialogFragment) {
            ((VideoDialogFragment) fragment).dismissAllowingStateLoss();
        }
        super.onDestroy();
    }
}