package com.datarecovery.master.dialog;

import android.content.Context;

import androidx.annotation.NonNull;


import com.datarecovery.master.dialog.BaseDialog;
import com.datarecovery.master.R;
import com.datarecovery.master.data.consts.Constants;
import com.datarecovery.master.databinding.DialogWechatPayQrCodeBinding;
import com.datarecovery.master.utils.QrCodeUtil;

import atmob.reactivex.rxjava3.disposables.Disposable;
import atmob.rxjava.utils.RxJavaUtil;

@BaseDialog.FullScreen
public class WechatPayQrCodeDialog extends BaseDialog<DialogWechatPayQrCodeBinding> {

    private Disposable generateQRDisposable;
    private @atmob.reactivex.rxjava3.annotations.NonNull Disposable queryOrderDisposable;
    private String orderId;
    private OrderDisposable orderDisposable;

    public WechatPayQrCodeDialog(@NonNull Context context) {
        super(context, R.style.Theme_Common_Dialog);
        binding.setOnCloseClickListener(v -> dismiss());
    }

    @Override
    protected void onDismiss() {
        super.onDismiss();
        binding.wechatPayQrCode.setImageBitmap(null);
        if (queryOrderDisposable != null && !queryOrderDisposable.isDisposed()) {
            queryOrderDisposable.dispose();
            orderDisposable.getOrderDisposable(orderId, Constants.PAYMENT_WAY_WECHAT_SCAN, true, true);
        }
        if (generateQRDisposable != null && !generateQRDisposable.isDisposed()) {
            generateQRDisposable.dispose();
        }
    }

    public void show(String qrCodeData, String orderId, OrderDisposable orderDisposable) {
        this.orderId = orderId;
        this.orderDisposable = orderDisposable;
        this.queryOrderDisposable = orderDisposable.getOrderDisposable(orderId, Constants.PAYMENT_WAY_WECHAT_SCAN, false, true);
        if (generateQRDisposable != null && !generateQRDisposable.isDisposed()) {
            generateQRDisposable.dispose();
        }
        generateQRDisposable = RxJavaUtil.doInBackground(() -> QrCodeUtil.generateQrCode(qrCodeData, 300, R.drawable.icon_wechat_payment),
                bitmap -> binding.wechatPayQrCode.setImageBitmap(bitmap), throwable -> {
                    // TODO: 24/8/2023 show error
                });
        super.show();
    }

    public String getCurrentOrderId() {
        return orderId;
    }

    public interface OrderDisposable {
        Disposable getOrderDisposable(String orderId, int payWay, boolean showLoading, boolean isReportPay);
    }
}