package com.meeting.demo.dependency.menu.toolbar.listener;

import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.huawei.cloudlink.openapi.HWMSdk;
import com.huawei.cloudlink.openapi.model.HWMUserState;
import com.huawei.hwmbiz.HWMBizSdk;
import com.huawei.hwmcommonui.ui.popup.dialog.base.ButtonParams;
import com.huawei.hwmcommonui.ui.popup.dialog.edit.EditDialog;
import com.huawei.hwmcommonui.ui.popup.dialog.edit.EditDialogBuilder;
import com.huawei.hwmconf.presentation.dependency.menu.IConfMenu;
import com.huawei.hwmconf.presentation.dependency.menu.v2.OnMenuItemClickListener;
import com.huawei.hwmconf.presentation.error.ErrorMessageFactory;
import com.huawei.hwmconf.sdk.model.conf.entity.AttendeeModel;
import com.huawei.hwmconf.sdk.model.conf.entity.ConfInfo;
import com.huawei.hwmconf.sdk.util.Utils;
import com.meeting.demo.R;
import com.meeting.demo.dependency.NeedCustomType;
import com.meeting.demo.dependency.SdkHelper;
import com.meeting.demo.utils.DemoUtil;
import com.meeting.demo.utils.VoiceRecordUtils;
import com.huawei.hwmfoundation.callback.HwmCallback;
import com.huawei.hwmfoundation.utils.PreferenceUtils;
import com.huawei.hwmfoundation.utils.StringUtil;
import com.huawei.hwmfoundation.utils.route.HCActivityManager;
import com.huawei.hwmlogger.HCLog;
import com.huawei.hwmsdk.enums.SDKERR;
import com.huawei.hwmsdk.enums.VideoWndDisplayMode;
import com.huawei.hwmsdk.model.result.RawAudioFrameSubscribeInfo;
import com.huawei.hwmsdk.model.result.VoicePrompts;

import java.nio.charset.Charset;

public class CustomOnMenuItemClickListener implements OnMenuItemClickListener {
    private static final String TAG = CustomOnMenuItemClickListener.class.getSimpleName();

    @Override
    public void onCustomMenuItemClick(IConfMenu confMenu, ConfInfo confInfo) {
        int menuId = confMenu.getId();
        if (menuId == R.id.conf_menu_custom_modify_render) {
            clickModifyRender();
        } else if (menuId == R.id.conf_menu_custom_leave_or_end_conf) {
            clickLeaveOrEndConf();
        } else if (menuId == R.id.conf_disable_voice_prompts_menu_custom) {
            disableVoicePrompts();
        } else if (menuId == R.id.conf_menu_custom_send_im_raw_msg) {
            clickSendIMRawMsg();
        } else if (menuId == R.id.conf_menu_custom_voice_record) {
            clickVoiceRecord();
        } else if (menuId == R.id.conf_menu_custom) {
            DemoUtil.showToast("点击了自定义菜单");
        } else if (menuId == R.id.more_menu) {
            DemoUtil.showToast("点击了自定义更多菜单");
        } else if (menuId == R.id.minimize_meeting_window) {
            DemoUtil.showToast("最小化会中窗口");
            HWMSdk.getOpenApi(DemoUtil.getApplication()).minimizeMeetingWindow();
        }
    }

    @Override
    public void onCustomAttendeeMenuItemClick(IConfMenu confMenu, ConfInfo confInfo, AttendeeModel attendeeModel) {
        int menuId = confMenu.getId();
        if (menuId == R.id.conf_menu_custom) {
            DemoUtil.showToast("点击了与会者自定义菜单 : " + (attendeeModel == null ? "null" : attendeeModel.getName()));
        } else if (menuId == R.id.more_menu) {
            DemoUtil.showToast("点击了与会者自定义更多菜单" + (attendeeModel == null ? "null" : attendeeModel.getName()));
        }
    }

    private void disableVoicePrompts() {
        VoicePrompts voicePrompts = new VoicePrompts();
        voicePrompts.setDisableMutePrompt(true);
        SDKERR result = HWMBizSdk.getBizOpenApi().disableVoicePrompts(voicePrompts);
        HCLog.i(TAG, "result code:" + result.getValue() + " desc:" + result.getDescription());
    }

    private void clickSendIMRawMsg() {
        HCLog.i(TAG, " resumed = " + HCActivityManager.getInstance().getResumeActivity());
        HWMBizSdk.getBizOpenApi().sendRawMessageToAll("测试会中消息二进制通道".getBytes(Charset.defaultCharset()), new HwmCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                Log.i(TAG, "sendRawMessageToAll success.");
                DemoUtil.showToast("点自定义菜单，发送二进制消息成功");
            }

            @Override
            public void onFailed(int retCode, String desc) {
                Log.i(TAG, "sendRawMessageToAll failed.");
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                DemoUtil.showToastDialog("sendRawMessageToAll", retCode, desc);
            }
        });
    }

    private void clickLeaveOrEndConf() {
        if (HWMUserState.HWM_STATE_IN_CONF == HWMSdk.getOpenApi(HWMBizSdk.getApplication()).getHWMUserState()) {
            if (SdkHelper.getInstance().isHost()) {
                HWMSdk.getOpenApi(HWMBizSdk.getApplication()).endConf(new HwmCallback<Integer>() {
                    @Override
                    public void onSuccess(Integer integer) {
                        Toast.makeText(HWMBizSdk.getApplication(), "已成功结束会议", Toast.LENGTH_SHORT)
                                .show();
                    }

                    @Override
                    public void onFailed(int retCode, String desc) {
                        HCLog.i(TAG, "endConf onFailed" + retCode + " " + desc);
                        String err = ErrorMessageFactory.create(retCode);
                        if (!TextUtils.isEmpty(err)) {
                            desc = err;
                        }
                        DemoUtil.showToastDialog("endConf", retCode, desc);
                    }
                });
            } else {
                HWMSdk.getOpenApi(HWMBizSdk.getApplication()).leaveConf(new HwmCallback<Integer>() {
                    @Override
                    public void onSuccess(Integer integer) {
                        Toast.makeText(HWMBizSdk.getApplication(), "已成功离开会议", Toast.LENGTH_SHORT)
                                .show();
                    }

                    @Override
                    public void onFailed(int retCode, String desc) {
                        HCLog.i(TAG, "leaveConf onFailed" + retCode + " " + desc);
                        String err = ErrorMessageFactory.create(retCode);
                        if (!TextUtils.isEmpty(err)) {
                            desc = err;
                        }
                        DemoUtil.showToastDialog("leaveConf", retCode, desc);
                    }
                });
            }
        } else {
            Toast.makeText(HWMBizSdk.getApplication(), "会议不存在 ", Toast.LENGTH_SHORT).show();
        }
    }

    private void clickModifyRender() {
        VideoWndDisplayMode local = VideoWndDisplayMode.enumOf(
                PreferenceUtils.read(PreferenceUtils.PREFERENCES_NAME, NeedCustomType.SHOW_CUSTOM_LOCAL_DISPLAY_MODE,
                        VideoWndDisplayMode.VIDEO_WND_DISPLAY_CROP.getValue(), DemoUtil.getApplication()));
        VideoWndDisplayMode remote = VideoWndDisplayMode.enumOf(
                PreferenceUtils.read(PreferenceUtils.PREFERENCES_NAME, NeedCustomType.SHOW_CUSTOM_REMOTE_DISPLAY_MODE,
                        VideoWndDisplayMode.VIDEO_WND_DISPLAY_AUTO_ADAPT.getValue(), DemoUtil.getApplication()));
        HWMBizSdk.getBizOpenApi().modifyRenderMode(local, remote, new HwmCallback<Integer>() {
            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG, "modifyRenderMode onFailed" + retCode + " " + desc);
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                DemoUtil.showToastDialog("modifyRenderMode", retCode, desc);
            }

            @Override
            public void onSuccess(Integer integer) {
                DemoUtil.showToast("设置渲染模式成功");
            }
        });
    }

    private void clickVoiceRecord() {
        boolean newVoiceRecordState = !VoiceRecordUtils.isVoiceRecordChecked();
        if (newVoiceRecordState) {
            EditDialogBuilder dialogBuilder = buildEditDialog((dialog, button, index) -> {
                String input = ((EditDialog) dialog).getInput();
                setAudioRawDataOutputConfig(true, StringUtil.string2Int(input, 200));
                dialog.dismiss();
            });
            dialogBuilder.show();
        } else {
            setAudioRawDataOutputConfig(false, 0);
        }
    }

    private void setAudioRawDataOutputConfig(boolean enable, int interval) {
        VoiceRecordUtils.setVoiceRecordChecked(enable);
        RawAudioFrameSubscribeInfo info = new RawAudioFrameSubscribeInfo();
        info.setEnable(enable);
        info.setInterval(interval);
        SDKERR result = HWMBizSdk.getBizOpenApi().setAudioRawDataOutputConfig(info);
        HCLog.i(TAG, "clickVoiceRecord result=" + result);
    }

    private EditDialogBuilder buildEditDialog(ButtonParams.OnDialogButtonClick buttonClick) {
        EditDialogBuilder editDialogBuilder = new EditDialogBuilder(Utils.getResContext());
        editDialogBuilder.setTitle("设置音频采集时间间隔（单位毫秒)")
                .setTitlePosition(Gravity.CENTER)
                .setTitleColor(R.color.hwmconf_dialog_title_gray)
                .setTitleSize(R.dimen.hwmconf_sp_20)
                .setMaxLength(6)
                .setInputType(InputType.TYPE_CLASS_NUMBER)
                .setHint("200")
                .addAction("确定", -1, -1, buttonClick);
        return editDialogBuilder;
    }
}
