package com.uiuipad.appstore.activity.details;

import android.content.Context;
import android.util.Log;

import com.trello.rxlifecycle4.RxLifecycle;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.uiuipad.appstore.base.BaseResponse;
import com.uiuipad.appstore.bean.AdminAppInfo;
import com.uiuipad.appstore.bean.AppClassBean;
import com.uiuipad.appstore.network.NetInterfaceManager;

import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.subjects.BehaviorSubject;

public class DetailsPresenter implements DetailsContact.Presenter {
    private Context mContext;

    DetailsPresenter(Context context) {
        this.mContext = context;
    }

    private DetailsContact.DetailsView mView;

    private BehaviorSubject<ActivityEvent> lifecycle;

    public void setLifecycle(BehaviorSubject<ActivityEvent> lifecycle) {
        this.lifecycle = lifecycle;
    }

    public BehaviorSubject<ActivityEvent> getLifecycle() {
        return lifecycle;
    }

    @Override
    public void attachView(DetailsContact.DetailsView view) {
        this.mView = view;
    }

    @Override
    public void detachView() {
        this.mView = null;
    }


    @Override
    public void getAdminAppDetails(long id) {
        NetInterfaceManager.getInstance().getAdminAppDetailsObservable(id)
                .compose(RxLifecycle.bindUntilEvent(lifecycle, ActivityEvent.DESTROY))
                .subscribe(new Observer<BaseResponse<AdminAppInfo>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.e("getAdminAppDetails", "onSubscribe: ");
                    }

                    @Override
                    public void onNext(@NonNull BaseResponse<AdminAppInfo> infoBaseResponse) {
                        Log.e("getAdminAppDetails", "onNext: " + infoBaseResponse);
                        if (infoBaseResponse.code == 200) {
                            mView.setAdminAppDetails(infoBaseResponse.data);
                        } else {
                            mView.setAdminAppDetails(null);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("getAdminAppDetails", "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.e("getAdminAppDetails", "onComplete: ");
                    }
                });
    }
}
