package com.meeting.demo.view.sdk;

import static com.huawei.hwmbiz.setting.constant.Constants.SWITCH_OFF_STR;
import static com.huawei.hwmbiz.setting.constant.Constants.SWITCH_ON_STR;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.huawei.cloudlink.openapi.HWMSdk;
import com.huawei.cloudlink.openapi.api.param.AnonymousJoinConfBySignatureParam;
import com.huawei.cloudlink.openapi.api.param.JoinConfParam;
import com.huawei.clpermission.CLPermConstant;
import com.huawei.hwmbiz.HWMBizSdk;
import com.huawei.hwmconf.presentation.error.ErrorMessageFactory;
import com.huawei.hwmconf.presentation.util.PermissionUtil;
import com.huawei.hwmconf.sdk.util.Utils;
import com.meeting.demo.R;
import com.meeting.demo.constant.ConfigConstant;
import com.meeting.demo.dependency.NeedCustomType;
import com.meeting.demo.utils.AppIdContants;
import com.meeting.demo.utils.DemoUtil;
import com.meeting.demo.utils.PreferencesUtil;
import com.meeting.demo.view.DemoActivity;
import com.meeting.demo.view.base.BaseDialogFragment;
import com.huawei.hwmfoundation.callback.HwmCancelableCallBack;
import com.huawei.hwmfoundation.utils.DeviceUtil;
import com.huawei.hwmlogger.HCLog;
import com.huawei.hwmsdk.model.result.AppAuthInfo;

public class QuickAnonymousJoinMeetingFragment extends BaseDialogFragment {
    public final static String TAG = QuickAnonymousJoinMeetingFragment.class.getSimpleName();
    private View rootView;
    private EditText appIdView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Dialog dialog = getDialog();
        if (dialog != null) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        rootView = inflater.inflate(R.layout.sdk_quick_anonymous_join_conf, container, false);
        appIdView = rootView.findViewById(R.id.meeting_appId);
        appIdView.setText(PreferencesUtil.getStringPreference(DemoUtil.getResContext(), ConfigConstant.KEY_APP_ID, AppIdContants.APP_ID));

        Button joinBtn = rootView.findViewById(R.id.join_btn);
        joinBtn.setOnClickListener(v -> joinConf(null));
        Button joinBtnWithActivity = rootView.findViewById(R.id.join_btn_with_demo_activity);
        joinBtnWithActivity.setOnClickListener(v -> joinConf(DemoActivity.getInstance()));
        return rootView;
    }

    private void joinConf(Activity activity) {
        TextView idView = rootView.findViewById(R.id.meeting_id);
        TextView name = rootView.findViewById(R.id.meeting_nickname);
        TextView tvNickNameCN = rootView.findViewById(R.id.meeting_nickname_cn);
        TextView tvNickNameEN = rootView.findViewById(R.id.meeting_nickname_en);
        TextView tvCorpTrustAppId = rootView.findViewById(R.id.meeting_corpTrustAppId);
        TextView passwordView = rootView.findViewById(R.id.meeting_pass);
        EditText randomView = rootView.findViewById(R.id.meeting_random);
        EditText userIdView = rootView.findViewById(R.id.meeting_userId);
        EditText corpIdView = rootView.findViewById(R.id.meeting_corpId);
        EditText expireTimeView = rootView.findViewById(R.id.meeting_expireTime);
        EditText nonceView = rootView.findViewById(R.id.meeting_nonce);
        EditText signatureView = rootView.findViewById(R.id.meeting_signature);
        EditText extendedFieldTv = rootView.findViewById(R.id.meeting_nickname_extended_field);


        String mId = idView.getText().toString();
        String nickName = name.getText().toString();
        String nickNameCN = tvNickNameCN.getText().toString().trim();
        String nickNameEN = tvNickNameEN.getText().toString().trim();
        String corpTrustAppId = tvCorpTrustAppId.getText().toString().trim();
        String random = randomView.getText().toString();
        String password = passwordView.getText().toString();
        String appId = appIdView.getText().toString();
        String userId = userIdView.getText().toString();
        String corpId = corpIdView.getText().toString();
        String extendedField = extendedFieldTv.getText().toString();
        long expireTime = 0;
        try {
            expireTime = Long.parseLong(expireTimeView.getText().toString());
        } catch (NumberFormatException e) {
            DemoUtil.showToast("expireTime输入异常");
        }
        String nonce = nonceView.getText().toString();
        String signature = signatureView.getText().toString();
        Switch enableMicSwitch = rootView.findViewById(R.id.switch_enable_mic);
        boolean enableMic = enableMicSwitch.isChecked();
        Switch enableCameraSwitch = rootView.findViewById(R.id.switch_enable_camera);
        boolean enableCamera = enableCameraSwitch.isChecked();
        Switch enableEarpieceSwitch = rootView.findViewById(R.id.switch_enable_earpiece);
        boolean enableEarpiece = enableEarpieceSwitch.isChecked();
        Switch supportLoginedJoinConfSwitch = rootView.findViewById(R.id.switch_enable_support_logined_join_conf);
        boolean supportLoginedJoinConf = supportLoginedJoinConfSwitch.isChecked();
        showLoading();

        AppAuthInfo appAuthInfo = new AppAuthInfo().setAppId(appId).setUserId(userId).setCorpId(corpId).setExpireTime(expireTime).setNonce(nonce).setSignature(signature);
        JoinConfParam joinConfParam = new AnonymousJoinConfBySignatureParam()
            .setConfRandom(random).setAppAuthInfo(appAuthInfo)
            .setSupportLoginedJoinConf(supportLoginedJoinConf)
            .setPassword(password)
            .setStopConflictConf(DemoUtil.needCustom(NeedCustomType.IS_STOP_CONFLICT_CONF))
            .setConfId(mId)
            .setNickname(TextUtils.isEmpty(nickName) ? DeviceUtil.getDeviceName(Utils.getApp()) : nickName)
            .setAliasCN(nickNameCN)
            .setAliasEN(nickNameEN)
            .setCorpTrustAppId(corpTrustAppId)
            .setExtendedField(extendedField)
            .setCameraOn(enableCamera && PermissionUtil.hasPermission(CLPermConstant.Type.CAMERA))
            .setMicOn(enableMic && PermissionUtil.hasPermission(CLPermConstant.Type.AUDIO))
            .setSpeakerOff(enableEarpiece);

        HWMBizSdk.getConfSysDaoApi().setIsTurnOnMic(enableMic ? SWITCH_ON_STR : SWITCH_OFF_STR).subscribe(
            res -> HCLog.i(TAG, "setIsTurnOnMic: " + res), throwable -> HCLog.e(TAG, throwable.toString())
        );
        HWMBizSdk.getConfSysDaoApi().setIsTurnOnCamera(enableCamera ? SWITCH_ON_STR : SWITCH_OFF_STR).subscribe(
            res -> HCLog.i(TAG, "setIsTurnOnCam: " + res), throwable -> HCLog.e(TAG, throwable.toString())
        );

        dojoinConf(joinConfParam, activity);
    }

    private void dojoinConf(JoinConfParam joinConfParam, Activity activity) {
        final HwmCancelableCallBack<Void> joinConfCallback = new HwmCancelableCallBack<Void>() {
            @Override
            public void onSuccess(Void ret) {
                doDismissDialogAndFragment();
            }

            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG,"joinConf onFailed" + retCode + " " + desc);
                doDismissDialogAndFragment();
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                DemoUtil.showToastDialog("加入会议", retCode, desc);
            }

            @Override
            public void onCancel() {
                doDismissDialogAndFragment();
            }
        };
        if (activity == null) {
            HWMSdk.getOpenApi(DemoUtil.getApplication()).joinConf(joinConfParam, joinConfCallback);
        } else {
            HWMSdk.getOpenApi(DemoUtil.getApplication()).joinConf(activity, joinConfParam, joinConfCallback);
        }
    }
}
