package com.huawei.hwmdemo.view.sdk;

import android.app.Activity;
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.JoinConfParam;
import com.huawei.cloudlink.openapi.api.param.PasswordJoinConfParam;
import com.huawei.cloudlink.openapi.api.param.RandomJoinConfParam;
import com.huawei.hwmbiz.contact.cache.MyInfoCache;
import com.huawei.hwmbiz.contact.cache.model.MyInfoModel;
import com.huawei.hwmconf.presentation.error.ErrorMessageFactory;
import com.huawei.hwmconf.sdk.util.Utils;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.delegate.DelegateHolder;
import com.huawei.hwmdemo.dependency.NeedCustomType;
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.hwmlogger.HCLog;

public class JoinMeetingFragment extends BaseDialogFragment {
    public final static String TAG = JoinMeetingFragment.class.getSimpleName();
    private View vRoot;
    private EditText etRandom;
    private EditText etDomain;

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


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getDialog() != null) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        vRoot = inflater.inflate(R.layout.sdk_join_conf, container, false);
        etRandom = vRoot.findViewById(R.id.meeting_random);
        etDomain = vRoot.findViewById(R.id.meeting_domain);
        if (DelegateHolder.getHwmFeatureDelegate().isRandomJoinConfSupported()) {
            etRandom.setVisibility(View.VISIBLE);
            etDomain.setVisibility(View.VISIBLE);
        } else {
            etRandom.setVisibility(View.GONE);
            etDomain.setVisibility(View.GONE);
        }
        vRoot.findViewById(R.id.switch_enable_earpiece).setVisibility(DelegateHolder.getHwmFeatureDelegate().isSwitchEarpieceSupported() ? View.VISIBLE : View.GONE);
        vRoot.findViewById(R.id.join_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                joinConf(null);
            }
        });

        Button joinConfWithActivity = vRoot.findViewById(R.id.join_btn_with_demo_activity);
        joinConfWithActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                joinConf(DemoActivity.getInstance());
            }
        });
        return vRoot;
    }

    private void joinConf(Activity activity) {
        TextView tvMeetingId = vRoot.findViewById(R.id.meeting_id);
        TextView tvNickName = vRoot.findViewById(R.id.meeting_nickname);
        TextView tvNickNameCN = vRoot.findViewById(R.id.meeting_nickname_cn);
        TextView tvNickNameEN = vRoot.findViewById(R.id.meeting_nickname_en);
        TextView tvPassword = vRoot.findViewById(R.id.meeting_pass);
        TextView tvCorpTrustAppId = vRoot.findViewById(R.id.meeting_corpTrustAppId);
        TextView tvCorpPrefixCode = vRoot.findViewById(R.id.corp_prefix_code);
        TextView extendedFieldTv = vRoot.findViewById(R.id.meeting_nickname_extended_field);

        String random = null;
        String domain = null;
        if (DelegateHolder.getHwmFeatureDelegate().isRandomJoinConfSupported()) {
            random = etRandom.getText().toString();
            domain = etDomain.getText().toString();
        }

        String meetingId = tvMeetingId.getText().toString();
        String nickName = tvNickName.getText().toString();
        String nickNameCN = tvNickNameCN.getText().toString().trim();
        String nickNameEN = tvNickNameEN.getText().toString().trim();
        String extendedField = extendedFieldTv.getText().toString().trim();
        String corpTrustAppId = tvCorpTrustAppId.getText().toString().trim();
        String password = tvPassword.getText().toString();
        String prefixCode = tvCorpPrefixCode.getText().toString();

        if (TextUtils.isEmpty(meetingId)) {
            DemoUtil.showToast("会议ID不能为空");
            return;
        }
        Switch cascadingConfSwitch = vRoot.findViewById(R.id.switch_to_cascading_conf);
        boolean isCascadingConf = cascadingConfSwitch.isChecked();

        Switch enableMicSwitch = vRoot.findViewById(R.id.switch_enable_mic);
        boolean enableMic = enableMicSwitch.isChecked();
        Switch enableCameraSwitch = vRoot.findViewById(R.id.switch_enable_camera);
        boolean enableCamera = enableCameraSwitch.isChecked();

        Switch enableEarpieceSwitch = vRoot.findViewById(R.id.switch_enable_earpiece);
        boolean isSpeakerOff = enableEarpieceSwitch.isChecked() && DelegateHolder.getHwmFeatureDelegate().isSwitchEarpieceSupported();
        showLoading();

        JoinConfParam joinConfParam;
        if (!TextUtils.isEmpty(random)) {
            joinConfParam = new RandomJoinConfParam()
                .setRandom(random)
                .setConfId(meetingId)
                .setNickname(nickName)
                .setAliasCN(nickNameCN)
                .setAliasEN(nickNameEN)
                .setCorpTrustAppId(corpTrustAppId)
                .setCameraOn(enableCamera)
                .setMicOn(enableMic)
                .setSpeakerOff(isSpeakerOff)
                .setDomain(domain)
                .setExtendedField(extendedField);
        } else {
            joinConfParam = new PasswordJoinConfParam()
                .setPassword(password)
                .setConfId(meetingId)
                .setNickname(TextUtils.isEmpty(nickName) ? getMyNickName() : nickName)
                .setAliasCN(nickNameCN)
                .setAliasEN(nickNameEN)
                .setCorpTrustAppId(corpTrustAppId)
                .setCameraOn(enableCamera)
                .setStopConflictConf(DemoUtil.needCustom(NeedCustomType.IS_STOP_CONFLICT_CONF))
                .setMicOn(enableMic)
                .setSpeakerOff(isSpeakerOff)
                .setCascadingConf(isCascadingConf)
                .setCorpPrefixCode(prefixCode)
                .setExtendedField(extendedField);
        }

        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);
        }
    }

    private String getMyNickName() {
        MyInfoModel myInfo = MyInfoCache.getInstance(Utils.getApp()).getMyInfoCacheSyn();
        if (myInfo == null) {
            return "";
        }
        return myInfo.getName();
    }
}
