package com.huawei.hwmdemo.view.sdkconfig;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;

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.hwmbiz.HWMBizSdk;
import com.huawei.hwmconf.presentation.error.ErrorMessageFactory;
import com.huawei.hwmconf.sdk.model.conf.entity.VmrInfoListModel;
import com.huawei.hwmconf.sdk.model.conf.entity.VmrInfoModel;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.dependency.NeedCustomType;
import com.huawei.hwmdemo.utils.DemoUtil;
import com.huawei.hwmdemo.view.BaseActivity;
import com.huawei.hwmdemo.view.DemoActivity;
import com.huawei.hwmfoundation.callback.HwmCallback;
import com.huawei.hwmfoundation.callback.HwmCancelableCallBack;
import com.huawei.hwmlogger.HCLog;
import com.huawei.hwmsdk.enums.ConfAllowJoinUserType;
import com.huawei.hwmsdk.model.param.ModifyVmrParam;

import java.lang.ref.WeakReference;

/**
 * 云会议室详情和编辑页面
 */
public class VmrConfDetailActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = VmrConfDetailActivity.class.getSimpleName();

    private static final int HANDLE_MESSAGE_GET_CONF_DETAIL_SUCCESS = 10001;

    private AlertDialog alertLoadingDialog;

    private EditText subjectText;

    private EditText guestPwd;

    private Switch openWaitingRoomSwitch;

    private TextView confIdTv;

    private TextView hostPwdTv;

    private TextView guestPwdTv;

    private TextView vmrIdTypeTv;

    private TextView maxPartiesTv;

    private Button editConfBtn;

    private Button joinConfBtn;

    private RadioGroup modeGroup;

    private ConfAllowJoinUserType confAllowJoinUserType;

    private VmrInfoModel vmrInfoModel;

    private Handler vmrConfDetailHandler = new VmrConfDetailHandler(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vmr_conf_detail_activity);
        initView();
        initData();
    }

    private void initView() {
        subjectText = findViewById(R.id.edit_subject);
        guestPwd = findViewById(R.id.edit_guest_pwd);
        openWaitingRoomSwitch = findViewById(R.id.edit_switch_open_waiting_room);
        editConfBtn = findViewById(R.id.edit_conf_btn);
        editConfBtn.setOnClickListener(this);
        editConfBtn.setEnabled(false);

        joinConfBtn = findViewById(R.id.join_conf_btn);
        joinConfBtn.setOnClickListener(this);
        joinConfBtn.setEnabled(false);

        hostPwdTv = findViewById(R.id.conf_detail_host_pwd);
        guestPwdTv = findViewById(R.id.conf_detail_guest_pwd);
        confIdTv = findViewById(R.id.conf_detail_conf_id);
        vmrIdTypeTv = findViewById(R.id.conf_detail_vmr_id_type);
        maxPartiesTv = findViewById(R.id.conf_detail_vmr_max_parties);

        modeGroup = findViewById(R.id.allow_group);
        ((RadioButton) 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) {
                    confAllowJoinUserType = ConfAllowJoinUserType.CONF_ALLOW_JOIN_ANYONE;
                } else if (id == R.id.allow_mode_enterprise) {
                    confAllowJoinUserType = ConfAllowJoinUserType.CONF_ALLOW_JOIN_IN_COMPANY_USER;
                } else {
                    confAllowJoinUserType = ConfAllowJoinUserType.CONF_ALLOW_JOIN_INVITED_USER;
                }
            }
        });
    }

    private void initData() {
        Intent intent = getIntent();
        Bundle bundle = null;
        if (intent != null) {
            bundle = intent.getExtras();
        }
        if (null != bundle) {
            String confId = bundle.getString("confid");
            updateConfDetail(confId);
        }
        getFragmentManager();
    }

    private void updateConfDetail(String confId) {
        HWMBizSdk.getBizOpenApi().getVmrInfoList(new HwmCallback<VmrInfoListModel>() {
            @Override
            public void onSuccess(VmrInfoListModel vmrInfoListModel) {
                for (VmrInfoModel model : vmrInfoListModel.getVmrInfoList()) {
                    if (TextUtils.equals(model.getVmrConferenceId(), confId)) {
                        Message message = Message.obtain(vmrConfDetailHandler);
                        message.what = HANDLE_MESSAGE_GET_CONF_DETAIL_SUCCESS;
                        message.obj = model;
                        message.sendToTarget();
                    }
                }
            }

            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.e(TAG, "getVmrList failed " + retCode);
            }
        });
    }

    private static void handleVmrConfDetail(VmrConfDetailActivity outer) {
        ConfAllowJoinUserType type = outer.vmrInfoModel.getConfAllowJoinUserType();
        outer.setConfAllowJoinUserType(type);
        outer.openWaitingRoomSwitch.setChecked(outer.vmrInfoModel.isOpenWaitingRoom());
        String confId = outer.vmrInfoModel.getVmrConferenceId();
        outer.confIdTv.setText(confId);
        outer.hostPwdTv.setText(outer.vmrInfoModel.getChairmanPwd());
        outer.guestPwdTv.setText(outer.vmrInfoModel.getGuestPwd());
        outer.vmrIdTypeTv.setText(outer.vmrInfoModel.getType().getDescription());
        outer.maxPartiesTv.setText(String.valueOf(outer.vmrInfoModel.getMaxParties()));

        outer.editConfBtn.setEnabled(true);
        outer.joinConfBtn.setEnabled(true);
        if (outer.guestPwd != null) {
            outer.guestPwd.setText(outer.vmrInfoModel.getGuestPwd());
        }
    }

    private void setConfAllowJoinUserType(ConfAllowJoinUserType confAllowJoinUserType) {
        this.confAllowJoinUserType = confAllowJoinUserType;
        if (ConfAllowJoinUserType.CONF_ALLOW_JOIN_ANYONE == confAllowJoinUserType) {
            ((RadioButton) findViewById(R.id.allow_mode_everyone)).setChecked(true);
        } else if (ConfAllowJoinUserType.CONF_ALLOW_JOIN_IN_COMPANY_USER == confAllowJoinUserType) {
            ((RadioButton) findViewById(R.id.allow_mode_enterprise)).setChecked(true);
        } else {
            ((RadioButton) findViewById(R.id.allow_mode_invite)).setChecked(true);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.edit_conf_btn) {
            showGlobalLoading();
            doModifyVmrInfo();
        } else if (v.getId() == R.id.join_conf_btn) {
            joinVmrConf(null);
        } else if (v.getId() == R.id.join_conf_btn_with_demo_activity) {
            joinVmrConf(DemoActivity.getInstance());
        }
    }

    private void doModifyVmrInfo() {
        ModifyVmrParam vmrParam = new ModifyVmrParam();
        vmrParam.setGuestPwd(guestPwd.getText().toString());
        vmrParam.setHostPwd(vmrInfoModel.getChairmanPwd());
        vmrParam.setVmrId(vmrInfoModel.getVmrId());
        vmrParam.setSubject(subjectText.getText().toString());
        vmrParam.setConfAllowJoinUser(confAllowJoinUserType);
        vmrParam.setIsOpenWaitingRoom(openWaitingRoomSwitch.isChecked());
        HWMBizSdk.getBizOpenApi().changeVmrInfo(vmrParam, new HwmCallback<Void>() {
            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG, "change vmr info onFailed " + retCode + " desc " + desc);
                dismissGlobalLoading();
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                DemoUtil.showToastDialog("changeVmrInfo", retCode, desc);
            }

            @Override
            public void onSuccess(Void unused) {
                DemoUtil.showToast("修改Vmr信息成功");
                dismissGlobalLoading();
            }
        });
    }

    public void showGlobalLoading() {
        if (alertLoadingDialog == null) {
            alertLoadingDialog = new AlertDialog.Builder(this).create();
            alertLoadingDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            alertLoadingDialog.setCancelable(false);
            alertLoadingDialog.setOnKeyListener(
                (dialog, keyCode, event) -> keyCode == KeyEvent.KEYCODE_SEARCH || keyCode == KeyEvent.KEYCODE_BACK);
            alertLoadingDialog.setCanceledOnTouchOutside(false);

        }
        if (!isFinishing()) {
            alertLoadingDialog.show();
            alertLoadingDialog.setContentView(R.layout.loading_alert);
        }
    }

    public void dismissGlobalLoading() {
        if (null != alertLoadingDialog && alertLoadingDialog.isShowing()) {
            if (!isFinishing()) {
                alertLoadingDialog.dismiss();
            }
        }
    }

    private void joinVmrConf(Activity activity) {

        showGlobalLoading();

        JoinConfParam joinConfParam = new PasswordJoinConfParam().setConfId(vmrInfoModel.getVmrConferenceId())
            .setStopConflictConf(DemoUtil.needCustom(NeedCustomType.IS_STOP_CONFLICT_CONF))
            .setPassword(vmrInfoModel.getGuestPwd());

        final HwmCancelableCallBack<Void> joinConfCallback = new HwmCancelableCallBack<Void>() {
            @Override
            public void onSuccess(Void ret) {
                dismissGlobalLoading();
            }

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

            @Override
            public void onCancel() {
                dismissGlobalLoading();
            }
        };

        if (activity == null) {
            HWMSdk.getOpenApi(DemoUtil.getApplication()).joinConf(joinConfParam, joinConfCallback);
        } else {
            HWMSdk.getOpenApi(DemoUtil.getApplication()).joinConf(activity, joinConfParam, joinConfCallback);
        }
    }

    static class VmrConfDetailHandler extends Handler {

        private WeakReference<VmrConfDetailActivity> mOuter;

        public VmrConfDetailHandler(VmrConfDetailActivity activity) {
            mOuter = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            VmrConfDetailActivity outer = mOuter.get();
            if ((null != outer) && msg.what == HANDLE_MESSAGE_GET_CONF_DETAIL_SUCCESS) {
                HCLog.i(TAG, "get conf detail success.");
                outer.vmrInfoModel = (VmrInfoModel) msg.obj;
                outer.subjectText.setText(outer.vmrInfoModel.getName());
                handleVmrConfDetail(outer);
            } else {
                HCLog.e(TAG, "Invalid msg");
            }
            super.handleMessage(msg);
        }
    }
}
