package com.huawei.hwmdemo.view.scheme;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
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 android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;

import com.huawei.hwmbiz.login.api.AppIdAuthParam;
import com.huawei.hwmconf.presentation.error.ErrorMessageFactory;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.constant.ConfigConstant;
import com.huawei.hwmdemo.utils.AppIdContants;
import com.huawei.hwmdemo.utils.DemoUtil;
import com.huawei.hwmdemo.utils.LoginUtil;
import com.huawei.hwmdemo.utils.PreferencesUtil;
import com.huawei.hwmfoundation.callback.HwmCallback;

public class LinkAppWithNonceFragment extends DialogFragment {
    public final static String TAG = LinkAppWithNonceFragment.class.getSimpleName();
    View rootView;

    EditText expireTimeView;
    EditText userIdView;
    EditText userNameView;


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        rootView = inflater.inflate(R.layout.link_app_with_nonce, container, false);

        Button loginBtn = rootView.findViewById(R.id.login_btn);
        EditText appIdView = rootView.findViewById(R.id.app_id);
        expireTimeView = rootView.findViewById(R.id.expire_time);
        userIdView = rootView.findViewById(R.id.user_id);
        userNameView = rootView.findViewById(R.id.user_name);


        appIdView.setText(PreferencesUtil.getStringPreference(this.getActivity().getApplicationContext(), ConfigConstant.KEY_APP_ID, AppIdContants.APP_ID));
        appIdView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                PreferencesUtil.setStringPreferences(LinkAppWithNonceFragment.this.getActivity().getApplicationContext(), ConfigConstant.KEY_APP_ID, editable.toString());
            }
        });
        expireTimeView.setText(String.valueOf(AppIdContants.EXPIRE_TIME));


        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
        return rootView;
    }

    private void login() {
        linkAppWithNonce();
    }

    private void linkAppWithNonce() {
        AppIdAuthParam param = buildLoginParam();
        TextView addressView = rootView.findViewById(R.id.anonymous_server_address);
        String serverAddress =  addressView.getText().toString();

        TextView portView = rootView.findViewById(R.id.anonymous_server_port);
        String portString = portView.getText().toString();

        if (TextUtils.isEmpty(serverAddress)) {
            Toast.makeText(this.getContext(),"服务器地址不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(portString)) {
            Toast.makeText(this.getContext(),"端口不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        Switch checkedSSL = rootView.findViewById(R.id.checked_ssl);

        LoginUtil.LoginParamEx loginParamEx = new LoginUtil.LoginParamEx(serverAddress, portString, checkedSSL.isChecked());

        LoginUtil.getAppIdLoginNonce(param, loginParamEx, new HwmCallback<String>() {
            @Override
            public void onFailed(int retCode, String desc) {
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                String finalDesc = desc;
                new Handler(Looper.getMainLooper()).post(() -> DemoUtil.showToastDialog("getAppIdLoginNonce", retCode, finalDesc));
            }

            @Override
            public void onSuccess(String nonce) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    doNonceLinkApp(nonce);
                    DemoUtil.showToast("NonceLinkApp with nonce " + nonce);
                });
            }
        });
    }

    private AppIdAuthParam buildLoginParam() {


        TextView nonceView = rootView.findViewById(R.id.nonce);
        String nonce = nonceView.getText().toString();
        TextView signatureView = rootView.findViewById(R.id.signature);
        String signature = signatureView.getText().toString();
        String userId = userIdView.getText().toString();
        String userName = userNameView.getText().toString();



        long expireTime = 0;
        String expireTimeValue = expireTimeView.getText().toString();

        try {
            expireTime = Long.parseLong(expireTimeValue);
        } catch (NumberFormatException e) {
            DemoUtil.showToast("签名过期时间输入异常");
        }

        AppIdAuthParam appIdAuthParam = new AppIdAuthParam();
        appIdAuthParam.setExpireTime(expireTime);
        appIdAuthParam.setNonce(nonce);
        appIdAuthParam.setCorpId("");
        appIdAuthParam.setThirdUserId(userId);
        appIdAuthParam.setSignature(signature);
        appIdAuthParam.setUserName(userName);
        appIdAuthParam.setDeptCode("");

        return appIdAuthParam;
    }

    private void doNonceLinkApp(String nonce) {
        String startUrl = "cloudlink://welinksoftclient/h5page?page=launch&nonce=" + nonce;
        DemoUtil.openCloudLinkWithURL(getContext(),startUrl);
    }
}
