package com.huawei.hwmdemo.view.sdk;

import android.graphics.Bitmap;
import android.os.Bundle;
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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.huawei.hwmbiz.HWMBizSdk;
import com.huawei.hwmcommonui.ui.popup.dialog.slider.SliderDialog;
import com.huawei.hwmcommonui.ui.popup.dialog.slider.SliderDialogBuilder;
import com.huawei.hwmcommonui.ui.view.verifycode.SliderCaptcha;
import com.huawei.hwmcommonui.utils.DensityUtil;
import com.huawei.hwmconf.sdk.model.login.entity.CheckControllerSliderParam;
import com.huawei.hwmconf.sdk.model.login.entity.RequestControllerSliderParam;
import com.huawei.hwmconf.sdk.model.login.entity.RequestPairParam;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.utils.ControllerUtils;
import com.huawei.hwmdemo.utils.DemoUtil;
import com.huawei.hwmdemo.view.base.BaseDialogFragment;
import com.huawei.hwmfoundation.utils.BitmapUtil;
import com.huawei.hwmfoundation.utils.DeviceUtil;
import com.huawei.hwmfoundation.utils.FileUtil;
import com.huawei.hwmsdk.common.SdkCallback;
import com.huawei.hwmsdk.enums.SDKERR;
import com.huawei.hwmsdk.model.result.CheckControllerSliderResult;
import com.huawei.hwmsdk.model.result.RequestControllerSliderResult;
import com.huawei.hwmsdk.model.result.RequestPairResult;

import java.nio.charset.StandardCharsets;
import java.util.Locale;

public class OfflineControllerFragment extends BaseDialogFragment implements SliderCaptcha.Listener {

    private String verificationId;
    private String sliderToken;

    private SliderDialog mSliderDialog;

    // 滑块dialog的宽度固定为312dp
    private static final int SLIDER_DIALOG_WIDTH = 312;
    private EditText pairCodeEditText;
    private Button pairButton;
    private ViewGroup verificationCodeArea;
    private EditText verificationCodeEditText;
    private View pairCodeArea;

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

        pairCodeArea = rootView.findViewById(R.id.pair_code_area);
        pairCodeEditText = rootView.findViewById(R.id.pair_code_input);
        verificationCodeArea = rootView.findViewById(R.id.verification_code_area);
        verificationCodeEditText = rootView.findViewById(R.id.verification_code_input);

        verificationCodeArea.setVisibility(View.GONE);

        pairButton = rootView.findViewById(R.id.pair_btn);
        pairButton.setOnClickListener(view -> requestSlider());
        return rootView;
    }

    private void requestSlider() {
        showLoading();

        String deviceId = FileUtil.encryptSHA256(
                DeviceUtil.getAndroidId(DemoUtil.getApplication()).getBytes()
        );
        RequestControllerSliderParam requestControllerSliderParam = new RequestControllerSliderParam();
        requestControllerSliderParam.setDeviceId(deviceId);
        requestControllerSliderParam.setWidth(280);
        requestControllerSliderParam.setHeight(110);
        HWMBizSdk.getBizOpenApi().requestControllerSlider(requestControllerSliderParam, new SdkCallback<RequestControllerSliderResult>() {
            @Override
            public void onFailed(SDKERR error) {
                OfflineControllerFragment.this.dismissLoading();
                DemoUtil.showToast(error.getDescription());
            }

            @Override
            public void onSuccess(RequestControllerSliderResult result) {
                OfflineControllerFragment.this.dismissLoading();

                verificationId = result.getVerificationId();
                showSliderDialog(result.getCutImage(), result.getShadowImage(), result.getPointY());
            }
        });
    }

    private void showSliderDialog(String cutImage, String shadowImage, int pointY) {
        if (isRemoving()) {
            return;
        }

        Bitmap sliderBitmap = BitmapUtil.stringToBitmap(cutImage);
        Bitmap shadowBitmap = BitmapUtil.stringToBitmap(shadowImage);
        float scale = getScale(shadowBitmap);
        if (mSliderDialog == null) {
            mSliderDialog = new SliderDialogBuilder(getContext())
                    .setShadowImage(BitmapUtil.createBlockBitmap(shadowBitmap, scale))
                    .setSliderImage(sliderBitmap, scale)
                    .setSliderListener(this)
                    .setPointY(pointY)
                    .show();
        } else {
            mSliderDialog.setShadowImage(BitmapUtil.createBlockBitmap(shadowBitmap, scale));
            mSliderDialog.setSliderImage(sliderBitmap, scale);
            mSliderDialog.setPointY(pointY);
            mSliderDialog.resetSeekbar();
            if (!mSliderDialog.isShowing()) {
                mSliderDialog.show();
            }
        }
    }

    private float getScale(Bitmap shadowBitmap) {
        if (shadowBitmap == null) {
            return 0;
        }
        int dialogWidth = DensityUtil.dp2px(SLIDER_DIALOG_WIDTH);
        return dialogWidth * 1.0f / shadowBitmap.getWidth();
    }

    @Override
    public void onClickRefreshImage() {
        requestSlider();
    }

    @Override
    public void onCheckSliderImage(int pointX, int slideTime) {
        if (isRemoving()) {
            return;
        }
        CheckControllerSliderParam checkControllerSliderParam = new CheckControllerSliderParam();
        checkControllerSliderParam.setPointX(pointX);
        checkControllerSliderParam.setSlideTime(slideTime);
        checkControllerSliderParam.setVerificationId(verificationId);

        HWMBizSdk.getBizOpenApi().checkControllerSlider(checkControllerSliderParam, new SdkCallback<CheckControllerSliderResult>() {
            @Override
            public void onFailed(SDKERR error) {
                if (error == SDKERR.USG_SLIDER_VERIFY_CODE_ERROR) {
                    //用户滑块位置校验失败
                    showSliderCheckResult(false);
                    requestSlider();
                }
                DemoUtil.showToast(error.getDescription());
            }

            @Override
            public void onSuccess(CheckControllerSliderResult checkControllerSliderResult) {
                showSliderCheckResult(true);
                if (mSliderDialog != null) {
                    mSliderDialog.dismiss();
                    mSliderDialog = null;
                }
                sliderToken = checkControllerSliderResult.getToken();

                checkPairCode();
            }
        });
    }

    private void checkPairCode() {
        RequestPairParam requestPairParam = new RequestPairParam();
        requestPairParam.setPairCode(pairCodeEditText.getText().toString().toUpperCase(Locale.ENGLISH));
        requestPairParam.setToken(sliderToken);
        requestPairParam.setDeviceId(FileUtil.encryptSHA256(DeviceUtil.getAndroidId(DemoUtil.getApplication())
                .getBytes(StandardCharsets.UTF_8)));
        HWMBizSdk.getBizOpenApi().requestPair(requestPairParam, new SdkCallback<RequestPairResult>() {
            @Override
            public void onFailed(SDKERR error) {
                if (error == SDKERR.SDK_LOGINLOGIC_NEED_REPAIR_WITH_CREDENTIAL) {
                    DemoUtil.showToast("请输入验证码");

                    pairCodeArea.setVisibility(View.GONE);
                    verificationCodeArea.setVisibility(View.VISIBLE);

                    pairCodeEditText.clearFocus();
                    verificationCodeEditText.clearFocus();
                    pairButton.setText("验证");
                    pairButton.setOnClickListener(view -> checkVerificationCode());
                    return;
                }
                DemoUtil.showToast(error.getDescription());
            }

            @Override
            public void onSuccess(RequestPairResult requestPairResult) {

            }
        });
    }

    private void checkVerificationCode() {
        RequestPairParam requestPairParam = new RequestPairParam();
        requestPairParam.setToken(sliderToken);
        requestPairParam.setPairCode(pairCodeEditText.getText().toString().toUpperCase(Locale.ENGLISH));
        requestPairParam.setVerifyCode(verificationCodeEditText.getText().toString());
        requestPairParam.setDeviceId(FileUtil.encryptSHA256(DeviceUtil.getAndroidId(DemoUtil.getApplication())
                .getBytes(StandardCharsets.UTF_8)));
        HWMBizSdk.getBizOpenApi().requestPair(requestPairParam, new SdkCallback<RequestPairResult>() {
            @Override
            public void onFailed(SDKERR error) {
                DemoUtil.showToast(error.getDescription());
            }

            @Override
            public void onSuccess(RequestPairResult requestPairResult) {
                dismiss();
                ControllerUtils.goRouteControllerH5Page(getContext(), requestPairResult.getNonce(),
                        requestPairResult.getCode(), true);
            }
        });
    }

    public void showSliderCheckResult(boolean isSuccessful) {
        if (mSliderDialog != null) {
            mSliderDialog.setSeekbarThumbVisibility(View.GONE);
            mSliderDialog.setSliderSeekbarResultVisibility(View.VISIBLE);
            mSliderDialog.setSliderVerifyResultImage(isSuccessful
                    ? getContext().getDrawable(R.drawable.hwmconf_slider_vertification_success) :
                    getContext().getDrawable(R.drawable.hwmconf_slider_vertification_failed));
            mSliderDialog.setSliderVerifyResultText(isSuccessful
                    ? getString(R.string.hwmconf_successful_verification) :
                    getString(R.string.hwmconf_drag_again));
            if (!mSliderDialog.isShowing()) {
                mSliderDialog.show();
            }
        }
    }
}
