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

import com.casic.dcms.bean.LoginResultBean;
import com.casic.dcms.listener.OnLoginListener;
import com.casic.dcms.mvp.model.ILoginInModel;
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 LoginInModelImpl implements ILoginInModel {

    private final OnLoginListener loginListener;

    public LoginInModelImpl(OnLoginListener listener) {
        this.loginListener = listener;
    }

    /**
     * {@link ILoginInModel}
     */
    @Override
    public Subscription sendLoginInRequest(String username, String password) {
        Observable<LoginResultBean> observable = RetrofitServiceManager.getTokenData(username, password);
        return observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<LoginResultBean>() {
            @Override
            public void onCompleted() {

            }

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

            @Override
            public void onNext(LoginResultBean resultBean) {
                if (resultBean != null) {
                    loginListener.onSuccess(resultBean);
                }
            }
        });
    }
}
