package com.meeting.demo.view.sdk;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.RadioGroup;

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

import com.huawei.cloudlink.openapi.HWMSdk;
import com.meeting.demo.R;
import com.meeting.demo.dependency.NeedCustomType;
import com.meeting.demo.model.ModeType;
import com.meeting.demo.utils.DemoUtil;
import com.meeting.demo.vision.utils.ModeUtil;
import com.meeting.demo.view.base.BaseDialogFragment;
import com.huawei.hwmfoundation.utils.PreferenceUtils;

public class SelectModeFragment extends BaseDialogFragment {

    public final static String TAG = ServerSettingFragment.class.getSimpleName();

    private RadioGroup mRgMode;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getDialog() != null) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        View vRoot = inflater.inflate(R.layout.fragment_select_mode, container, false);
        mRgMode = vRoot.findViewById(R.id.rg_mode);
        initRadioGroup();
        View btnSave = vRoot.findViewById(R.id.btn_save);
        btnSave.setEnabled(!HWMSdk.getOpenApi(DemoUtil.getApplication()).isActivated());
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int checkedId = mRgMode.getCheckedRadioButtonId();
                if (checkedId == R.id.rb_mobile) {
                    ModeUtil.setModeType(DemoUtil.getApplication(), ModeType.MOBILE);
                } else if (checkedId == R.id.rb_vision) {
                    ModeUtil.setModeType(DemoUtil.getApplication(), ModeType.VISION);
                    // 异步初始化启动大屏会崩溃 切大屏时选择同步初始化
                    PreferenceUtils.save(PreferenceUtils.PREFERENCES_NAME, NeedCustomType.ASYNC_INIT_SDK_CONFIG, false, DemoUtil.getApplication());
                }
                dismiss();
                showLoading();
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    dismissLoading();
                    DemoUtil.restartApplication();
                }, 1500L);
            }
        });
        return vRoot;
    }

    private void initRadioGroup() {
        ModeType modeType = ModeUtil.getModeType(DemoUtil.getApplication());
        if (modeType == ModeType.MOBILE) {
            mRgMode.check(R.id.rb_mobile);
        } else if (modeType == ModeType.VISION) {
            mRgMode.check(R.id.rb_vision);
        }
    }
}
