package com.casic.dcms.mvp.model.impl;

import com.casic.dcms.bean.PublicKeyBean;
import com.casic.dcms.listener.OnAuthenticateListener;
import com.casic.dcms.mvp.model.IAuthenticateModel;
import com.casic.dcms.utils.retrofit.RetrofitServiceManager;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class AuthenticateModelImpl implements IAuthenticateModel {

    private final OnAuthenticateListener onAuthenticateListener;

    public AuthenticateModelImpl(OnAuthenticateListener listener) {
        this.onAuthenticateListener = listener;
    }

    /**
     * {@link IAuthenticateModel}
     */
    @Override
    public Subscription sendAuthenticateRequest() {
        Observable<PublicKeyBean> observable = RetrofitServiceManager.authenticate();
        return observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<PublicKeyBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (e.getCause() != null) {
                    onAuthenticateListener.onFailure(e);
                }
            }

            @Override
            public void onNext(PublicKeyBean key) {
                if (key != null) {
                    onAuthenticateListener.onSuccess(key);
                }
            }
        });
    }
}
