package com.datarecovery.master.data.repositories;


import com.datarecovery.master.data.api.AtmobApi;
import com.datarecovery.master.data.api.request.MemberDetailRequest;
import com.datarecovery.master.data.api.request.MemberPayRequest;
import com.datarecovery.master.data.api.request.PaymentStatusRequest;
import com.datarecovery.master.data.api.response.MemberDetailResponse;
import com.datarecovery.master.data.api.response.MemberPayResponse;
import com.datarecovery.master.data.api.response.PaymentStatusResponse;
import com.datarecovery.master.module.member.MemberType;
import com.datarecovery.master.utils.BoxingUtil;
import com.datarecovery.master.utils.RxHttpHandler;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Singleton;

import atmob.reactivex.rxjava3.core.Single;
import atmob.rxjava.utils.RxJavaUtil;

@Singleton
public class MemberRepository {


    private final AtmobApi atmobApi;
    private final DeviceFuncRepository deviceFuncRepository;

    @Inject
    public MemberRepository(AtmobApi atmobApi, DeviceFuncRepository deviceFuncRepository) {
        this.atmobApi = atmobApi;
        this.deviceFuncRepository = deviceFuncRepository;
    }


    public Single<MemberDetailResponse> memberDetail(@MemberType String type) {
        return atmobApi.memberDetail(new MemberDetailRequest(type))
                .compose(RxHttpHandler.handle(false))
                .compose(RxJavaUtil.SingleSchedule.io2Main());
    }

    public Single<MemberPayResponse> requestPayOrder(int itemId, int payPlatform, int payMethod) {
        return atmobApi.requestPayOrder(new MemberPayRequest(itemId, payPlatform, payMethod))
                .compose(RxHttpHandler.handle(false))
                .compose(RxJavaUtil.SingleSchedule.io2Main());
    }


    /**
     * 0-查询失败，继续轮询
     * 1-未支付，继续轮询
     * 2-支付成功
     * 3-支付关闭
     * 4-已退款
     */
    public Single<Boolean> getPayStatus(String orderId) {
        return atmobApi.getPayStatus(new PaymentStatusRequest(orderId))
                .compose(RxHttpHandler.handle(false))
                .map(PaymentStatusResponse::getStatus)
                .map(integer -> {
                    if (BoxingUtil.boxing(integer) == 0 || BoxingUtil.boxing(integer) == 1) {
                        throw new Exception("支付未完成, status ==> " + integer);
                    }
                    return integer;
                })
                .retryWhen(RxJavaUtil.retryWhen(null, 100, 3, TimeUnit.SECONDS))
                .onErrorReturnItem(0)
                .map(integer -> integer == 2)
                .compose(RxJavaUtil.SingleSchedule.io2Main())
                .doOnTerminate(deviceFuncRepository::refreshFuncAuths);
    }
}
