package com.meeting.demo.view.scheme;

import android.net.Uri;
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.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

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

public class LoginedLinkJoinFragment extends LinkJoinFragment {
    public final static String TAG = LoginedLinkJoinFragment.class.getSimpleName();

    View rootView;
    Switch fakeNonceSwitch;

    EditText expireTimeView;

    EditText userIdView;
    EditText userNameView;

    Switch checkedSSL;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = super.onCreateView(inflater, container, savedInstanceState);
        rootView.findViewById(R.id.user_id_layout).setVisibility(View.VISIBLE);

        fakeNonceSwitch = rootView.findViewById(R.id.switch_use_fake_nonce);
        fakeNonceSwitch.setVisibility(View.VISIBLE);

        View signatureLayout = rootView.findViewById(R.id.signature_layout);
        signatureLayout.setVisibility(View.VISIBLE);

        View expireTimeLayout = rootView.findViewById(R.id.expire_time_layout);
        expireTimeLayout.setVisibility(View.VISIBLE);
        expireTimeView = rootView.findViewById(R.id.expire_time);
        expireTimeView.setText(String.valueOf(AppIdContants.EXPIRE_TIME));

        View userIdLayout = rootView.findViewById(R.id.user_id_layout);
        userIdLayout.setVisibility(View.VISIBLE);
        userIdView = rootView.findViewById(R.id.user_id);

        userNameView = rootView.findViewById(R.id.anonymous_name);

        View appIdLayout = rootView.findViewById(R.id.app_id_layout);
        appIdLayout.setVisibility(View.VISIBLE);
        EditText appIdView = rootView.findViewById(R.id.app_id);
        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(LoginedLinkJoinFragment.this.getActivity().getApplicationContext(), ConfigConstant.KEY_APP_ID, editable.toString());
            }
        });
        View nonceLayout = rootView.findViewById(R.id.nonce_layout);
        nonceLayout.setVisibility(View.VISIBLE);

        checkedSSL = rootView.findViewById(R.id.checked_ssl);
        checkedSSL.setVisibility(View.VISIBLE);
        return rootView;
    }

    @Override
    public void doLinkJoin(@NonNull LinkJoinParam param) {
        if (fakeNonceSwitch.isChecked()) {
            String fakeNonce = DemoUtil.getRandomString(10);
            doLinkJoin(fakeNonce, param);
            HCLog.i(TAG,"use fake nonce");
            return;
        }
        TextView nonceView = rootView.findViewById(R.id.nonce);
        String nonce = nonceView.getText().toString();

        String userId = ((TextView) rootView.findViewById(R.id.user_id)).getText().toString();
        if (TextUtils.isEmpty(userId)) {
            Toast.makeText(this.getContext(),"用户id不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String signature = ((TextView) rootView.findViewById(R.id.signature)).getText().toString();
        if (TextUtils.isEmpty(userId)) {
            Toast.makeText(this.getContext(),"signature不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        long expireTime = 0;
        String expireTimeValue = expireTimeView.getText().toString();

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

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

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



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

        LoginUtil.getAppIdLoginNonce(appIdAuthParam, loginParamEx, new HwmCallback<String>() {
            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG,"getAppIdLoginNonce onFailed" + retCode + " " + 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) {
                doLinkJoin(nonce, param);
            }
        });

    }

    private void doLinkJoin(String nonce, LinkJoinParam param) {
        try {
            Uri.Builder builder = new Uri.Builder().scheme("cloudlink")
                .authority("welinksoftclient")
                .path("h5page")
                .appendQueryParameter("page", "LoginAndJoinConf")
                .appendQueryParameter("server_url", param.serverAddress)
                .appendQueryParameter("port", param.portString)
                .appendQueryParameter("conf_id", param.confId)
                .appendQueryParameter("enter_code", param.enterCode)
                .appendQueryParameter("name", param.name)
                .appendQueryParameter("open_mic", String.valueOf(param.openMic))
                .appendQueryParameter("open_camera", String.valueOf(param.openCamera))
                .appendQueryParameter("nonce", nonce);
            DemoUtil.openAppWithURL(getActivity(), builder.toString());
        } catch (UnsupportedOperationException e) {
            Log.e(TAG, e.getMessage());
        }

    }
}
