package com.oo.eye.mvp.presenter;

import android.content.Context;

import com.app.baselibrary.commonUtil.SnUtils;
import com.oo.eye.bean.EyeHistroyBean;
import com.oo.eye.db.DbManager;
import com.oo.eye.mvp.contract.EyeHistroyContract;
import com.oo.eye.net.EyeDataManager;
import com.oo.seex.netlibrary.net.response.NewResponseImpl;
import com.oo.seex.netlibrary.net.response.RxCallback;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xucon on 2017/12/26.
 */

public class EyeHistroyPresenter implements EyeHistroyContract.Presenter {

	private EyeHistroyContract.View mView;

	public EyeHistroyPresenter(EyeHistroyContract.View view){
		this.mView = view;
	}


	private void getEyeHistroyDB(Context context, int page, int limit){
		try {
			QueryBuilder builder = DbManager.getDaoMaster(context).newSession().getEyeHistroyBeanDao().queryBuilder();
			List<EyeHistroyBean> beans = builder.limit(page * limit).build().list();
			int count = builder.build().list().size();
			if (mView != null && mView.isActive()) {
				mView.getEyeHistroyDBSuccee(beans, page, count);
			}
		}catch (Exception e){
			e.printStackTrace();
			if (mView != null && mView.isActive()) {
				mView.getEyeHistroyFail("数据加载失败");
			}
		}
	}

	public void getEyeHistroy(Context context, boolean isNet, int page, int limit){
		if(isNet){
			getEyeHistroyNet(page,limit);
		}else{
			getEyeHistroyDB(context,page,limit);
		}
	}

	private void getEyeHistroyNet(int page,int limit){
		EyeDataManager.getInstance().getEyeTestData(SnUtils.getSN(),page,limit)
			.subscribe(new RxCallback<NewResponseImpl<ArrayList<EyeHistroyBean>>>() {
					@Override
					public void onSuccess(NewResponseImpl<ArrayList<EyeHistroyBean>> response) {
						if(mView != null && mView.isActive()){
							if(response.isSuccess()){
								mView.getEyeHistroyNetSuccee(response.getData(),response.getPage());
							}else{
								mView.getEyeHistroyFail("数据获取失败");
							}
						}
					}

					@Override
					public void onError(int errorCode, String errorMessage) {
						if(mView != null && mView.isActive()){
							mView.getEyeHistroyFail("数据获取失败");
						}
					}
				});
	}
}
