package com.huawei.hwmdemo.view.sdk;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;

import androidx.annotation.NonNull;

import com.huawei.cloudlink.openapi.HWMSdk;
import com.huawei.cloudlink.openapi.api.param.CallParam;
import com.huawei.cloudlink.openapi.api.param.StartCtdConfParam;
import com.huawei.cloudlink.openapi.api.param.StartP2PConfParam;
import com.huawei.cloudlink.openapi.model.HWMUserState;
import com.huawei.hwmbiz.HWMBizSdk;
import com.huawei.hwmbiz.login.cache.LoginStatusCache;
import com.huawei.hwmconf.presentation.error.ErrorMessageFactory;
import com.huawei.hwmconf.sdk.model.conf.entity.AttendeeModel;
import com.huawei.hwmconf.sdk.model.conf.entity.CalleeInfo;
import com.huawei.hwmconf.sdk.model.conf.entity.CallerInfo;
import com.huawei.hwmconf.sdk.model.conf.entity.ConfInfo;
import com.huawei.hwmconf.sdk.model.conf.entity.JoinConfPermissionType;
import com.huawei.hwmconf.sdk.model.conf.entity.MeetingType;
import com.huawei.hwmconf.sdk.util.Utils;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.delegate.DelegateHolder;
import com.huawei.hwmdemo.utils.DemoUtil;
import com.huawei.hwmdemo.view.DemoActivity;
import com.huawei.hwmdemo.view.base.BaseDialogFragment;
import com.huawei.hwmfoundation.callback.HwmCancelableCallBack;
import com.huawei.hwmfoundation.utils.PhoneNumUtil;
import com.huawei.hwmlogger.HCLog;
import com.huawei.hwmsdk.enums.SDKERR;

public class P2PConfFragment extends BaseDialogFragment {
    public final static String TAG = P2PConfFragment.class.getSimpleName();

    private View rootView;

    private RadioButton useNewP2PBtn;

    private RadioButton useCtdConfBtn;

    private RadioButton usePrevP2PBtn;

    private EditText calleeThirdAccountIdView;

    private EditText calleeNumberView;

    private EditText calleeAccountView;

    private EditText calleeAccountUuidView;

    private EditText calleeNickNameView;

    private EditText calleeAliasCNView;

    private EditText calleeAliasENView;

    private EditText calleeCorpIdView;

    private EditText calleeExtendedField;

    private EditText callerNickNameView;

    private EditText callerAliasCNView;

    private EditText callerAliasENView;

    private EditText callerNumberView;

    private EditText callerCorpIdView;

    private EditText callerExtendedField;

    private RadioButton audioBtn;

    private Switch isGuestJoinConfWithoutPwdSwitch;

    private Switch enableEarpieceSwitch;

    private RadioGroup modeGroup;

    private Button callBtn;

    private Button callBtnWithActivity;

    private EditText customMsg;

    private JoinConfPermissionType joinConfPermissionType = JoinConfPermissionType.PERMIT_EVERYONE;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        rootView = inflater.inflate(R.layout.sdk_p2p_conf, container, false);
        useNewP2PBtn = rootView.findViewById(R.id.new_p2p_conf);
        usePrevP2PBtn = rootView.findViewById(R.id.prev_call_conf);
        useCtdConfBtn = rootView.findViewById(R.id.ctd_call_conf);
        calleeThirdAccountIdView = rootView.findViewById(R.id.callee_third_account_id);
        calleeNumberView = rootView.findViewById(R.id.callee_number);
        calleeAccountView = rootView.findViewById(R.id.callee_account);
        calleeAccountUuidView = rootView.findViewById(R.id.callee_account_uuid);
        calleeAccountUuidView.setVisibility(View.GONE);
        calleeNickNameView = rootView.findViewById(R.id.callee_nickname);
        calleeAliasCNView = rootView.findViewById(R.id.callee_aliasCN);
        calleeAliasENView = rootView.findViewById(R.id.callee_aliasEN);
        calleeCorpIdView = rootView.findViewById(R.id.callee_corp_id);
        calleeExtendedField = rootView.findViewById(R.id.callee_ExtendedField);

        callerNickNameView = rootView.findViewById(R.id.caller_nickname);
        callerAliasCNView = rootView.findViewById(R.id.caller_aliasCN);
        callerAliasENView = rootView.findViewById(R.id.caller_aliasEN);
        callerNumberView = rootView.findViewById(R.id.caller_callback_number);
        callerCorpIdView = rootView.findViewById(R.id.caller_corp_id);
        callerExtendedField = rootView.findViewById(R.id.caller_ExtendedField);

        customMsg = rootView.findViewById(R.id.custom_message);

        audioBtn = rootView.findViewById(R.id.radio_audio);

        isGuestJoinConfWithoutPwdSwitch = rootView.findViewById(R.id.switch_is_guest_without_pwd);
        enableEarpieceSwitch = rootView.findViewById(R.id.switch_enable_earpiece);

        modeGroup = rootView.findViewById(R.id.allow_group);
        ((RadioButton)rootView.findViewById(R.id.allow_mode_everyone)).setChecked(true);
        modeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int id) {
                if (id == R.id.allow_mode_everyone) {
                    joinConfPermissionType = JoinConfPermissionType.PERMIT_EVERYONE;
                } else if (id == R.id.allow_mode_enterprise) {
                    joinConfPermissionType = JoinConfPermissionType.PERMIT_ENTERPRISE_USER;
                } else {
                    joinConfPermissionType = JoinConfPermissionType.PERMIT_INVITED_USER;
                }
            }
        });

        usePrevP2PBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (callBtnWithActivity == null) {
                    return;
                }
                callBtnWithActivity.setVisibility(isChecked ? View.GONE : View.VISIBLE);
            }
        });

        callBtn = rootView.findViewById(R.id.start_call);
        callBtnWithActivity = rootView.findViewById(R.id.start_call_with_demo_activity);
        initOnClickListener();

        return rootView;
    }

    private void initOnClickListener() {
        if (callBtn != null) {
            callBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (HWMUserState.HWM_STATE_IDLE == HWMSdk.getOpenApi(HWMBizSdk.getApplication()).getHWMUserState()) {
                        boolean useNewP2P = useNewP2PBtn.isChecked();
                        boolean useCtdConf = useCtdConfBtn.isChecked();
                        if (useNewP2P) {
                            startP2PConf(null);
                        } else if (useCtdConf) {
                            startCtdConf(null);
                        } else {
                            startCall();
                        }
                    } else {
                        DemoUtil.showToast("您当前正在呼叫或者有进行中的会议！");
                    }
                }
            });
        }

        if (callBtnWithActivity != null) {
            callBtnWithActivity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (HWMUserState.HWM_STATE_IDLE == HWMSdk.getOpenApi(HWMBizSdk.getApplication()).getHWMUserState()) {
                        boolean useNewP2P = useNewP2PBtn.isChecked();
                        boolean useCtdConf = useCtdConfBtn.isChecked();
                        if (useNewP2P) {
                            startP2PConf(DemoActivity.getInstance());
                        } else if (useCtdConf) {
                            startCtdConf(DemoActivity.getInstance());
                        } else {
                            startCall();
                        }
                    } else {
                        DemoUtil.showToast("您当前正在呼叫或者有进行中的会议！");
                    }
                }
            });
        }
    }

    private void startP2PConf(Activity activity) {
        if (!LoginStatusCache.isLogin()) {
            HCLog.e(TAG, "not login, create conf failed");
            DemoUtil.showToastDialog("createConf", SDKERR.SDK_LOGIN_E_ERR_NOT_LOGINED.getValue(),
                    "Not logged in, not available:此业务未登录不可用");
            return;
        }
        showLoading();
        boolean isVideo = !audioBtn.isChecked();
        boolean isSpeakerOff = enableEarpieceSwitch.isChecked() && DelegateHolder.getHwmFeatureDelegate().isSwitchEarpieceSupported();
        StartP2PConfParam startP2PConfParam = new StartP2PConfParam();
        startP2PConfParam.setCallerInfo(genP2PConfCaller());
        startP2PConfParam.setCalleeInfo(genP2PConfCallee());
        startP2PConfParam.setMeetingType(isVideo ? MeetingType.CONF_VIDEO : MeetingType.CONF_AUDIO);
        startP2PConfParam.setConfAllowJoinUser(joinConfPermissionType);
        startP2PConfParam.setGuestJoinConfWithoutPwd(isGuestJoinConfWithoutPwdSwitch.isChecked());
        startP2PConfParam.setSpeakerOff(isSpeakerOff);
        startP2PConfParam.setCustomInfo(customMsg.getText().toString());

        final HwmCancelableCallBack<ConfInfo> startP2PConfCallback = new HwmCancelableCallBack<ConfInfo>() {
            @Override
            public void onSuccess(ConfInfo confInfo) {
                Log.i(TAG, "startP2PConf success");
                doDismissDialogAndFragment();
            }

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

            @Override
            public void onCancel() {
                HCLog.i(TAG, "startP2PConf onCancel");
                dismissLoading();
            }
        };

        if (activity == null) {
            HWMSdk.getOpenApi(DemoUtil.getApplication()).startP2PConf(startP2PConfParam, startP2PConfCallback);
        } else {
            HWMSdk.getOpenApi(DemoUtil.getApplication()).startP2PConf(activity, startP2PConfParam, startP2PConfCallback);
        }
    }

    private CallerInfo genP2PConfCaller() {
        CallerInfo callerInfo = new CallerInfo(callerNickNameView.getText().toString());
        callerInfo.setAliasCN(callerAliasCNView.getText().toString());
        callerInfo.setAliasEN(callerAliasENView.getText().toString());
        callerInfo.setOrgId(callerCorpIdView.getText().toString());
        callerInfo.setExtendedField(callerExtendedField.getText().toString());
        return callerInfo;
    }

    private CalleeInfo genP2PConfCallee() {
        String nickName = calleeNickNameView.getText().toString();
        CalleeInfo calleeInfo = new CalleeInfo(nickName);
        String thirdAccountId = calleeThirdAccountIdView.getText().toString();
        calleeInfo.setThirdUserId(thirdAccountId);
        String number = calleeNumberView.getText().toString();
        calleeInfo.setNumber(number);
        calleeInfo.setAliasCN(calleeAliasCNView.getText().toString());
        calleeInfo.setAliasEN(calleeAliasENView.getText().toString());
        calleeInfo.setOrgId(calleeCorpIdView.getText().toString());
        calleeInfo.setExtendedField(calleeExtendedField.getText().toString());
        return calleeInfo;
    }

    private void startCtdConf(Activity activity) {
        StartCtdConfParam startCtdConfParam = new StartCtdConfParam();
        AttendeeModel callerInfo = new AttendeeModel();
        callerInfo.setName(callerNickNameView.getText().toString());
        callerInfo.setAliasCN(callerAliasCNView.getText().toString());
        callerInfo.setAliasEN(callerAliasENView.getText().toString());
        callerInfo.setNumber(callerNumberView.getText().toString());
        callerInfo.setExtendedField(callerExtendedField.getText().toString());
        startCtdConfParam.setCallerInfo(callerInfo);
        // 被叫
        AttendeeModel calleeInfo = new AttendeeModel();
        calleeInfo.setName(calleeAccountView.getText().toString());
        calleeInfo.setAliasCN(calleeAliasCNView.getText().toString());
        calleeInfo.setAliasEN(calleeAliasENView.getText().toString());
        calleeInfo.setNumber(calleeNumberView.getText().toString());
        calleeInfo.setExtendedField(calleeExtendedField.getText().toString());
        startCtdConfParam.setCalleeInfo(calleeInfo);
        startCtdConfParam.setGuestJoinConfWithoutPwd(isGuestJoinConfWithoutPwdSwitch.isChecked());

        final HwmCancelableCallBack<ConfInfo> startCtdConfCallback = new HwmCancelableCallBack<ConfInfo>() {
            @Override
            public void onCancel() {
                HCLog.i(TAG, "startCtdConf onCancel");
                dismissLoading();
            }

            @Override
            public void onSuccess(ConfInfo confInfo) {
                Log.i(TAG, "startCtdConf success");
                doDismissDialogAndFragment();
                DemoUtil.showToast(String.format(Utils.getResContext().getString(R.string.hwmconf_ctd_callbak_toast),
                        PhoneNumUtil.formatPhoneNumber(Utils.getApp(), callerInfo.getNumber())));
            }

            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG, "startCtdConf onFailed" + retCode + " " + desc);
                dismissLoading();
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                DemoUtil.showToastDialog("startCtdConf", retCode, desc);
            }
        };
        if (activity == null) {
            HWMSdk.getOpenApi(getActivity().getApplication()).startCtdConf(startCtdConfParam, startCtdConfCallback);
        } else {
            HWMSdk.getOpenApi(getActivity().getApplication()).startCtdConf(activity, startCtdConfParam, startCtdConfCallback);
        }
    }

    private void startCall() {
        String thirdAccountId = calleeThirdAccountIdView.getText().toString();
        String number = calleeNumberView.getText().toString();
        String account = calleeAccountView.getText().toString();
        String accountUuid = calleeAccountUuidView.getText().toString();
        String nickName = calleeNickNameView.getText().toString();

        boolean isVideo = !audioBtn.isChecked();
        if (TextUtils.isEmpty(number) && TextUtils.isEmpty(thirdAccountId) && TextUtils.isEmpty(account)) {
            DemoUtil.showToast("被叫sip号码/被叫三方账号id/被叫账号name不能同时为空");
            return;
        }
        showLoading();
        CallParam callParam = new CallParam().setVideo(isVideo);

        if (!TextUtils.isEmpty(number)) {
            //通过sip号码的方式进行呼叫
            callParam.setNumber(number);
        }

        if (!TextUtils.isEmpty(account)) {
            //通过华为企业通讯录工号的方式进行呼叫
            callParam.setAccount(account);
        }

        if (!TextUtils.isEmpty(accountUuid)) {
            //通过华为企业通讯录id的方式进行呼叫
            callParam.setCalleeUuid(accountUuid);
        }

        if (!TextUtils.isEmpty(thirdAccountId)) {
            //如果是appid的方式登录，可以通过第三方通讯录的联系人id进行呼叫
            callParam.setThirdAccountId(thirdAccountId);
        }

        if (!TextUtils.isEmpty(nickName)) {
            callParam.setNickName(nickName);
        }
        HWMSdk.getOpenApi(getActivity().getApplication()).startCall(callParam, new HwmCancelableCallBack<Void>() {
            @Override
            public void onSuccess(Void result) {
                Log.i(TAG, "startCall success");
                doDismissDialogAndFragment();
            }

            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG, "startCall onFailed" + retCode + " " + desc);
                dismissLoading();
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                DemoUtil.showToastDialog("旧立即会议发起", retCode, desc);
            }

            @Override
            public void onCancel() {
                HCLog.i(TAG, "startCall onCancel");
                dismissLoading();
            }
        });
    }
}
