package com.atmob.voiceai.data.repositories;


import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.atmob.app.lib.handler.RxHttpHandler;
import com.atmob.voiceai.data.api.AtmobApi;
import com.atmob.voiceai.data.api.bean.MemberInfoBean;
import com.atmob.voiceai.data.api.request.BaseRequest;
import com.atmob.voiceai.data.api.response.UserInfoResponse;

import java.util.concurrent.TimeUnit;

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

import atmob.reactivex.rxjava3.annotations.NonNull;
import atmob.reactivex.rxjava3.core.Single;
import atmob.reactivex.rxjava3.core.SingleObserver;
import atmob.reactivex.rxjava3.disposables.Disposable;
import atmob.rxjava.utils.RxJavaUtil;

@Singleton
public class AccountRepository {

    private final AtmobApi atmobApi;
    private final MemberRepository memberRepository;
    private boolean requestUserInfoDisabled;

    @Inject
    public AccountRepository(AtmobApi atmobApi, MemberRepository memberRepository) {
        this.atmobApi = atmobApi;
        this.memberRepository = memberRepository;
        refreshUserData();
    }



    private void refreshUserData() {
        if (requestUserInfoDisabled) {
            return;
        }
        userInfo().subscribe(new SingleObserver<UserInfoResponse>() {


            @Override
            public void onSubscribe(@NonNull Disposable d) {
                requestUserInfoDisabled = true;
            }

            @Override
            public void onSuccess(@NonNull UserInfoResponse userInfoResponse) {
                requestUserInfoDisabled = false;
            }

            @Override
            public void onError(@NonNull Throwable e) {
                requestUserInfoDisabled = false;
            }
        });
    }


    private Single<UserInfoResponse> userInfo() {
        return atmobApi.userInfo(new BaseRequest())
                .compose(RxHttpHandler.handle(true))
                .retryWhen(RxJavaUtil.exponentialBackOff(null, 3, TimeUnit.SECONDS))
                .compose(RxJavaUtil.SingleSchedule.io2Main())
                .doOnSuccess(userInfoResponse -> {
                    MemberInfoBean memberInfo = userInfoResponse.getMemberInfo();
                    memberRepository.setIsMember(memberInfo != null && memberInfo.isIsMember());
                });
    }
}
