package com.huawei.hwmdemo.view.sdk;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;

import com.huawei.cloudlink.openapi.HWMSdk;
import com.huawei.hwmbiz.HWMBizSdk;
import com.huawei.hwmbiz.eventbus.LoginResult;
import com.huawei.hwmbiz.login.api.SsoAuthParam;
import com.huawei.hwmconf.presentation.error.ErrorMessageFactory;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.utils.DemoUtil;
import com.huawei.hwmdemo.view.base.BaseDialogFragment;
import com.huawei.hwmdemo.view.webview.WebViewActivity;
import com.huawei.hwmfoundation.HwmContext;
import com.huawei.hwmfoundation.callback.HwmCallback;
import com.huawei.hwmlogger.HCLog;
import com.huawei.hwmsdk.enums.AuthServerType;

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

    private Context context;
    View rootView;

    TextView domainView;
    TextView codeView;

    ActivityResultLauncher<Intent> activityResultLauncher;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.sdk_sso_login, container, false);
        initView();
        Button joinBtn = rootView.findViewById(R.id.sso_login_btn);
        joinBtn.setOnClickListener(v -> login());

        Button codeBtn = rootView.findViewById(R.id.sso_code_btn);
        codeBtn.setOnClickListener(v -> getCode());

        Button schemaBtn = rootView.findViewById(R.id.sso_schema_btn);
        schemaBtn.setOnClickListener(v -> doSchemaSsoLogin());
        return rootView;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        activityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Intent data = result.getData();
                    HwmContext.getInstance().runOnMainThread(() -> {
                        codeView.setText(data.getStringExtra("result"));
                    });
                }
            });
    }

    //通过配置，把默认值绑定在界面
    private void initView() {
        domainView = rootView.findViewById(R.id.ssologin_company_domain);
        codeView = rootView.findViewById(R.id.ssologin_code);
    }

    private void doSchemaSsoLogin() {
        String domain = domainView.getText().toString();
        if (TextUtils.isEmpty(domain)) {
            DemoUtil.showToast("domain参数不能为空");
            return;
        }

        getSSOAuthorizeUrlAndDoSchema(domain);
    }

    // 获取鉴权地址后schema拉起入会
    private void getSSOAuthorizeUrlAndDoSchema(String domain) {
        showLoading();
        HWMBizSdk.getBizOpenApi().getSsoAuthInfo(domain, new HwmCallback<String>() {
            @Override
            public void onFailed(int retCode, String desc) {
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                DemoUtil.showToast("getSSOAuthorizeUrlAndDoSchema failed: " + desc);
                HCLog.i(TAG, "getSSOAuthorizeUrlAndDoSchema failed " + retCode);
                dismissLoading();
            }

            @Override
            public void onSuccess(String pageUrl) {
                dismissLoading();
                Intent intent = new Intent(SsoLoginFragment.this.getActivity(), WebViewActivity.class);
                intent.putExtra("requestUrl", pageUrl);
                startActivity(intent);
            }
        });
    }


    private void getCode() {
        String domain = domainView.getText().toString();
        if (TextUtils.isEmpty(domain)) {
            DemoUtil.showToast("domain参数不能为空");
            return;
        }
        getSSOAuthorizeUrlAndRequestCode(domain);
    }


    private void getSSOAuthorizeUrlAndRequestCode(String domain) {
        showLoading();
        HWMBizSdk.getBizOpenApi().getSsoAuthInfo(domain, new HwmCallback<String>() {
            @Override
            public void onFailed(int retCode, String desc) {
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                DemoUtil.showToast("getSSOAuthorizeUrlAndRequestCode failed: " + desc);
                HCLog.i(TAG, "getSSOAuthorizeUrlAndRequestCode failed " + retCode);
                dismissLoading();
            }

            @Override
            public void onSuccess(String pageUrl) {
                dismissLoading();

                Intent intent = new Intent(SsoLoginFragment.this.getActivity(), WebViewActivity.class);
                intent.putExtra("requestUrl", pageUrl);
                intent.putExtra("action", WebViewActivity.ACTION_GET_CODE);
                activityResultLauncher.launch(intent);
            }
        });
    }

    private void login() {
        String domain = domainView.getText().toString();
        String code = codeView.getText().toString();
        if (TextUtils.isEmpty(domain) || TextUtils.isEmpty(code)) {
            DemoUtil.showToast("参数不能为空");
            return;
        }

        showLoading();

        SsoAuthParam ssoAuthParam = new SsoAuthParam();
        ssoAuthParam.setDomain(domain);
        ssoAuthParam.setCode(code);
        ssoAuthParam.setAuthServerType(AuthServerType.AUTH_SERVER_TYPE_OAUTH2);
        HWMSdk.getOpenApi(getActivity().getApplication()).loginBySSO(ssoAuthParam, new HwmCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                dismissAndFinish();
                if (loginResult != null) {
                    DemoUtil.showToast("登录成功" + loginResult.getUserUuid() + "; account:" + loginResult.getAccount()
                        + "; thirdAccount:" + loginResult.getThirdAccount());
                } else {
                    DemoUtil.showToast("已登录");
                }
            }

            @Override
            public void onFailed(int retCode, String desc) {
                HwmContext.getInstance().runOnMainThread(() -> {
                    String err = ErrorMessageFactory.create(retCode);
                    if (TextUtils.isEmpty(err)) {
                        err = desc;
                    }
                    HCLog.i(TAG,"loginBySSO onFailed" + retCode + " " + err);
                    DemoUtil.showToastDialog("loginBySSO", retCode, desc);
                    dismissAndFinish();
                });
            }
        });
    }

    private void dismissAndFinish() {
        dismissLoading();
        getActivity().finish();
    }


}
