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

import com.casic.dcms.listener.OnGetLightDetailListener;
import com.casic.dcms.mvp.model.ILightDetailModel;
import com.casic.dcms.utils.retrofit.RetrofitServiceManager;

import java.io.IOException;

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

public class LightDetailModelImpl implements ILightDetailModel {

    private final OnGetLightDetailListener lightDetailListener;

    public LightDetailModelImpl(OnGetLightDetailListener listener) {
        this.lightDetailListener = listener;
    }

    /**
     * {@link com.casic.dcms.mvp.model.ILightDetailModel}
     */
    @Override
    public Subscription sendLightDetailRequest(String lampId) {
        Observable<ResponseBody> observable = RetrofitServiceManager.getLightDetailResult(lampId);
        return observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ResponseBody>() {
            @Override
            public void onCompleted() {

            }

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

            @Override
            public void onNext(ResponseBody resultBean) {
                if (resultBean != null) {
                    try {
                        lightDetailListener.onSuccess(resultBean.string());
                    } catch (IOException e) {
                        lightDetailListener.onFailure(e);
                    }
                }
            }
        });
    }
}
