/**
 * 鱼眼矫正功能 Helper
 * 从 EZRealPlayActivity 拆分出来，负责鱼眼设备的初始化、矫正模式弹窗、矫正类型切换等逻辑
 */
package com.videogo.ui.realplay.fec;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.videogo.openapi.EZConstants.EZFecCorrectType;
import com.videogo.openapi.EZConstants.EZFecPlaceType;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.realplay.RealPlayStatus;
import com.videogo.ui.playback.EZPlayBackListActivity;
import com.videogo.ui.realplay.EZRealPlayActivity;
import com.videogo.widget.CheckTextButton;

import ezviz.ezopensdk.R;

/**
 * 鱼眼矫正功能 Helper
 * 管理鱼眼设备的初始化、矫正模式切换、弹窗展示与关闭
 *
 * 使用方式：构造时传入所需引用和回调，无需 Activity 实现回调接口
 */
public class FecHelper {

    private final Context mContext;// 上下文，用于 inflate 布局
    private final EZDeviceInfo mDeviceInfo;// 设备信息
    private final EZPlayer mEZPlayer;// 播放器实例
    private final View mPlayerView;// 主播放视图（SurfaceView 或 TextureView）
    private final View mPopupAnchorView;// 弹窗 showAsDropDown 的 anchor 视图
    private final BooleanSupplier mIsPlayingSupplier;// 动态判断是否在播放中
    private final IntSupplier mPopupHeightSupplier;// 动态获取弹窗高度
    private final Runnable mSetForceOrientationZero;// 关闭弹窗时重置方向
    private final PopupWindowDismisser mDismisser;// 关闭 PopupWindow

    private PopupWindow mFecPopupWindow;// 鱼眼矫正模式pop
    private Button[] fecCorrectTypeButtons;// 鱼眼设备矫正模式按钮数组
    private EZFecPlaceType fecPlaceType;// 鱼眼安装模式
    private EZFecCorrectType fecCorrectType;// 鱼眼矫正模式
    private FecViewLayoutHelper fecViewLayoutHelper;// 鱼眼辅助类

    /**
     * @param context              上下文（用于 inflate 布局）
     * @param deviceInfo           设备信息
     * @param ezPlayer             播放器实例
     * @param playerView           主播放视图（SurfaceView 或 TextureView）
     * @param popupAnchorView    弹窗 showAsDropDown 的 anchor 视图
     * @param isPlayingSupplier    动态判断是否在播放中
     * @param popupHeightSupplier  动态获取弹窗高度（由 Activity 侧计算）
     * @param setForceOrientationZero 关闭弹窗时重置方向的回调
     * @param dismisser            关闭 PopupWindow 的回调
     */
    public FecHelper(Context context, EZDeviceInfo deviceInfo, EZPlayer ezPlayer,
                     View playerView, View popupAnchorView,
                     BooleanSupplier isPlayingSupplier,
                     IntSupplier popupHeightSupplier,
                     Runnable setForceOrientationZero,
                     PopupWindowDismisser dismisser) {
        this.mContext = context;
        this.mDeviceInfo = deviceInfo;
        this.mEZPlayer = ezPlayer;
        this.mPlayerView = playerView;
        this.mPopupAnchorView = popupAnchorView;
        this.mIsPlayingSupplier = isPlayingSupplier;
        this.mPopupHeightSupplier = popupHeightSupplier;
        this.mSetForceOrientationZero = setForceOrientationZero;
        this.mDismisser = dismisser;
    }

    /**
     * 从 Activity 构建 FecHelper 并完成 initFecView（收敛 Activity 中的 lambda 配置代码）
     * Activity 中只需一行调用：mFecHelper = FecHelper.createFromActivity(this);
     */
    public static FecHelper createFromRealPlayActivity(EZRealPlayActivity activity) {
        FecHelper helper = new FecHelper(activity, activity.mDeviceInfo, activity.mEZPlayer,
                activity.mSurfaceHelper.mRealPlaySv,
                activity.mRealPlayPlayRl,
                () -> activity.mStatus == RealPlayStatus.STATUS_PLAY,
                () -> activity.mLocalInfo.getScreenHeight() - activity.mPortraitTitleBar.getHeight()
                        - activity.mRealPlayPlayRl.getHeight()
                        - (activity.mRealPlayRect != null ? activity.mRealPlayRect.top : activity.mLocalInfo.getNavigationBarHeight()),
                () -> activity.mOrientationHelper.setForceOrientation(0),
                activity::dismissPopWindowPublic);
        CheckTextButton fullscreenButton = activity.findViewById(R.id.fullscreen_button);
        helper.initFecView(activity.getWindow().getDecorView(), fullscreenButton, R.id.realplay_viewtype_btn, () -> activity.mRealRatio = 1);
        return helper;
    }

    /**
     * 从回放页面 Activity 构建 FecHelper 并完成 initFecView
     * Activity 中只需一行调用：mFecHelper = FecHelper.createFromPlaybackActivity(this);
     */
    public static FecHelper createFromPlaybackActivity(EZPlayBackListActivity activity) {
        FecHelper helper = new FecHelper(activity, activity.mDeviceInfo, activity.mPlaybackPlayer,
                activity.mSurfaceHelper.getTextureView(),
                activity.controlArea,
                () -> activity.mStatus == com.videogo.ui.playback.RemoteListContant.STATUS_PLAYING,
                () -> activity.localInfo.getScreenHeight() - activity.mPortraitTitleBar.getHeight()
                        - activity.mPlaybackPlayRl.getHeight() - activity.controlArea.getHeight()
                        - (activity.mRemotePlayBackRect != null ? activity.mRemotePlayBackRect.top : activity.localInfo.getNavigationBarHeight()),
                () -> {},
                activity::dismissPopWindowPublic);
        if (isFecDevice(activity.mDeviceInfo)) {
            activity.mCloudVideoActiveImg.setVisibility(android.view.View.GONE);// 页面太挤，云存储开通图片不显示
        }
        helper.initFecView(activity.getWindow().getDecorView(), activity.mOrientationHelper.getFullscreenButton(),
                R.id.remote_playback_viewtype_btn, () -> activity.mOrientationHelper.mRealRatio = 1);
        return helper;
    }

    /**
     * 判断指定设备是否为鱼眼设备
     */
    public static boolean isFecDevice(EZDeviceInfo deviceInfo) {
        return FecViewLayoutHelper.isFecDevice(deviceInfo);
    }

    /**
     * 鱼眼设备专用初始化
     * @param rootView  Activity 的根视图
     * @param fullscreenButton 全屏按钮（鱼眼设备需隐藏）
     * @param viewTypeBtnId  "查看模式"按钮的资源ID
     * @param realRatioSetter  设置画面比例的回调
     */
    public void initFecView(View rootView, View fullscreenButton, int viewTypeBtnId, Runnable realRatioSetter) {
        if (!FecViewLayoutHelper.isFecDevice(mDeviceInfo)) {
            return;
        }
        // 鱼眼设备显示"查看模式" & 调整画面比例为1:1
        fullscreenButton.setVisibility(View.GONE);// 鱼眼设备不支持全屏，隐藏全屏按钮
        ImageButton viewTypeBtn = (ImageButton) rootView.findViewById(viewTypeBtnId);
        viewTypeBtn.setVisibility(View.VISIBLE);
        viewTypeBtn.setOnClickListener(v -> openFecViewModePopupWindow(mPopupAnchorView));

        fecPlaceType = EZFecPlaceType.EZ_FEC_PLACE_CEILING;// demo中默认顶装
        fecCorrectType = EZFecCorrectType.EZ_FEC_CORRECT_FISH;// demo中默认鱼眼（原始码流）
        realRatioSetter.run();

        RelativeLayout realPlayPtzRL = rootView.findViewById(R.id.play_ptz_rl);
        SurfaceView sv1 = (SurfaceView) rootView.findViewById(R.id.play_sv1);
        SurfaceView sv2 = (SurfaceView) rootView.findViewById(R.id.play_sv2);
        SurfaceView sv3 = (SurfaceView) rootView.findViewById(R.id.play_sv3);
        SurfaceView sv4 = (SurfaceView) rootView.findViewById(R.id.play_sv4);
        SurfaceView sv5 = (SurfaceView) rootView.findViewById(R.id.play_sv5);
        SurfaceView sv6 = (SurfaceView) rootView.findViewById(R.id.play_sv6);
        ViewGroup playWindowVg = (ViewGroup) rootView.findViewById(R.id.vg_play_window);

        // fecViewLayoutHelper.fecPopupWindow 需要延后设置，全局搜索查看
        fecViewLayoutHelper = new FecViewLayoutHelper(mContext);
        fecViewLayoutHelper.playerView = mPlayerView;
        fecViewLayoutHelper.playWindowVg = playWindowVg;
        fecViewLayoutHelper.player = mEZPlayer;
        fecViewLayoutHelper.playPtzRL = realPlayPtzRL;
        SurfaceView[] surfaceViews = new SurfaceView[]{sv1, sv2, sv3, sv4, sv5, sv6};
        fecViewLayoutHelper.setSurfaceViews(surfaceViews);
        playWindowVg.post(() -> fecViewLayoutHelper.setPlayViewAspectRadioWith1V1());
    }

    /**
     * 播放成功后，应用当前鱼眼矫正模式
     */
    public void onPlaySucceed() {
        if (fecViewLayoutHelper != null) {
            fecViewLayoutHelper.openFecCorrect(fecCorrectType, fecPlaceType);
        }
    }

    /**
     * 播放停止或失败时，重置鱼眼状态
     */
    public void onPlayStopped() {
        if (fecViewLayoutHelper != null) {
            fecViewLayoutHelper.resetFecType();
            closeFecViewModePopupWindow();
        }
    }

    /**
     * 打开鱼眼矫正模式操作弹出框
     * @param parent 弹窗挂载的父视图
     */
    public void openFecViewModePopupWindow(View parent) {
        closeFecViewModePopupWindow();

        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        ViewGroup layoutView = (ViewGroup) layoutInflater.inflate(R.layout.realplay_fec_wnd, null, true);
        layoutView.findViewById(R.id.fec_close_btn).setOnClickListener(v -> closeFecViewModePopupWindow());

        Button placeWallBtn = layoutView.findViewById(R.id.fec_place_wall);
        Button placeFloorBtn = layoutView.findViewById(R.id.fec_place_floor);
        Button placeCeilingBtn = layoutView.findViewById(R.id.fec_place_ceiling);
        Button correctFishBtn = layoutView.findViewById(R.id.fec_correct_fish);
        Button correct4PtzBtn = layoutView.findViewById(R.id.fec_correct_4ptz);
        Button correct5PtzBtn = layoutView.findViewById(R.id.fec_correct_5ptz);
        Button correctFull5PtzBtn = layoutView.findViewById(R.id.fec_correct_full5ptz);
        Button correctLatBtn = layoutView.findViewById(R.id.fec_correct_lat);
        Button correctARCHorBtn = layoutView.findViewById(R.id.fec_correct_arc_hor);
        Button correctARCVerBtn = layoutView.findViewById(R.id.fec_correct_arc_ver);
        Button correctWideAngleBtn = layoutView.findViewById(R.id.fec_correct_wide_angle);
        Button correct180Btn = layoutView.findViewById(R.id.fec_correct_180);
        Button correct360Btn = layoutView.findViewById(R.id.fec_correct_360);
        Button correctCycBtn = layoutView.findViewById(R.id.fec_correct_cyc);
        fecCorrectTypeButtons = new Button[] {
                correct4PtzBtn, correct5PtzBtn, correctFull5PtzBtn,
                correctLatBtn, correctARCHorBtn, correctARCVerBtn,
                correctWideAngleBtn, correct180Btn, correct360Btn,
                correctCycBtn
        };

        View.OnClickListener fecWndClickListener = this::onFecWndClick;
        placeWallBtn.setOnClickListener(fecWndClickListener);
        placeFloorBtn.setOnClickListener(fecWndClickListener);
        placeCeilingBtn.setOnClickListener(fecWndClickListener);
        correctFishBtn.setOnClickListener(fecWndClickListener);
        correct4PtzBtn.setOnClickListener(fecWndClickListener);
        correct5PtzBtn.setOnClickListener(fecWndClickListener);
        correctFull5PtzBtn.setOnClickListener(fecWndClickListener);
        correctLatBtn.setOnClickListener(fecWndClickListener);
        correctARCHorBtn.setOnClickListener(fecWndClickListener);
        correctARCVerBtn.setOnClickListener(fecWndClickListener);
        correctWideAngleBtn.setOnClickListener(fecWndClickListener);
        correct180Btn.setOnClickListener(fecWndClickListener);
        correct360Btn.setOnClickListener(fecWndClickListener);
        correctCycBtn.setOnClickListener(fecWndClickListener);
        // 设置按钮的可见和可用状态
        int wallTypeValue = FecViewLayoutHelper.getSupportInt(EZFecPlaceType.EZ_FEC_PLACE_WALL, mDeviceInfo);
        int floorTypeValue = FecViewLayoutHelper.getSupportInt(EZFecPlaceType.EZ_FEC_PLACE_FLOOR, mDeviceInfo);
        int ceilingTypeValue = FecViewLayoutHelper.getSupportInt(EZFecPlaceType.EZ_FEC_PLACE_CEILING, mDeviceInfo);
        placeWallBtn.setVisibility(wallTypeValue > 0 ? View.VISIBLE : View.GONE);
        placeFloorBtn.setVisibility(floorTypeValue > 0 ? View.VISIBLE : View.GONE);
        placeCeilingBtn.setVisibility(ceilingTypeValue > 0 ? View.VISIBLE : View.GONE);
        setFecCorrectTypeBtnsEnable(fecPlaceType);

        int height = mPopupHeightSupplier.getAsInt();
        mFecPopupWindow = new PopupWindow(layoutView, LayoutParams.MATCH_PARENT, height, true);
        mFecPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mFecPopupWindow.setAnimationStyle(R.style.popwindowUpAnim);
        mFecPopupWindow.setFocusable(false);
        mFecPopupWindow.setOutsideTouchable(false);
        mFecPopupWindow.showAsDropDown(parent);
        mFecPopupWindow.update();

        fecViewLayoutHelper.fecPopupWindow = mFecPopupWindow;
    }

    /**
     * 关闭鱼眼查看模式操作弹出框
     */
    public void closeFecViewModePopupWindow() {
        if (mFecPopupWindow != null) {
            mDismisser.dismiss(mFecPopupWindow);
            mFecPopupWindow = null;
            fecViewLayoutHelper.fecPopupWindow = null;// fecViewLayoutHelper中的窗口对象置空，必须
            mSetForceOrientationZero.run();
        }
    }

    /**
     * 根据安装模式和能力集设置哪些矫正模式可用
     */
    private void setFecCorrectTypeBtnsEnable(EZFecPlaceType fecPlaceType) {
        int supportValue = FecViewLayoutHelper.getSupportInt(fecPlaceType, mDeviceInfo);
        FecViewLayoutHelper.setFecCorrectButtonsState(fecCorrectTypeButtons, supportValue);
    }

    /**
     * 鱼眼矫正模式的点击事件
     */
    private void onFecWndClick(View v) {
        // 没有在播放，拦截
        if (!mIsPlayingSupplier.getAsBoolean()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.fec_place_wall || id == R.id.fec_place_floor || id == R.id.fec_place_ceiling) {// 壁装 || 底装 || 顶装
            fecPlaceType = EZFecPlaceType.values()[Integer.parseInt(String.valueOf(v.getTag()))];
            setFecCorrectTypeBtnsEnable(fecPlaceType);
        } else if (id == R.id.fec_correct_fish || id == R.id.fec_correct_4ptz || id == R.id.fec_correct_5ptz ||
                id == R.id.fec_correct_full5ptz || id == R.id.fec_correct_lat || id == R.id.fec_correct_arc_hor ||
                id == R.id.fec_correct_arc_ver || id == R.id.fec_correct_wide_angle || id == R.id.fec_correct_180 ||
                id == R.id.fec_correct_360 || id == R.id.fec_correct_cyc) {
            // 默认鱼眼|| 4分屏 || 5分屏 || 全景5分屏 || 维度拉伸 || ARC || ARCV || 广角 || 180°全景 || 360°全景 || 柱状
            fecCorrectType = FecViewLayoutHelper.getFecCorrectTypeFromTag(Integer.parseInt(String.valueOf(v.getTag())));
            fecViewLayoutHelper.openFecCorrect(fecCorrectType, fecPlaceType);
        }
    }

    /**
     * 获取内部的 FecViewLayoutHelper 实例（供外部需要时调用）
     */
    public FecViewLayoutHelper getFecViewLayoutHelper() {
        return fecViewLayoutHelper;
    }

    /**
     * 当前是否已初始化（即当前设备是否为鱼眼设备且已完成初始化）
     */
    public boolean isInitialized() {
        return fecViewLayoutHelper != null;
    }


    /**
     * 动态获取 boolean 值的接口
     */
    public interface BooleanSupplier {
        boolean getAsBoolean();
    }

    /**
     * 动态获取 int 值的接口
     */
    public interface IntSupplier {
        int getAsInt();
    }

    /**
     * PopupWindow 关闭接口（因 RootActivity.dismissPopWindow 为 protected）
     */
    public interface PopupWindowDismisser {
        void dismiss(PopupWindow popupWindow);
    }
}
