package com.oo.eye.mvp.presenter;

import android.content.Context;

import com.app.baselibrary.commonUtil.SnUtils;
import com.oo.eye.EyeConfig;
import com.oo.eye.bean.EyeChartsBean;
import com.oo.eye.db.DbManager;
import com.oo.eye.gen.EyeChartsBeanDao;
import com.oo.eye.mvp.contract.EyeChartsContract;
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 EyeChartsPresenter implements EyeChartsContract.Presenter {

	private EyeChartsContract.View mView;

	public EyeChartsPresenter(EyeChartsContract.View view){
		this.mView = view;
	}

	public void getEyeChartsData(Context context, int limit){
		if(EyeConfig.getInstance().isNetData()){
			getEyeChartsNet(limit);
		}else{
			getEyeChartsDB(context,limit);
		}
	}

	private void getEyeChartsDB(Context context, int limit){
		try {
			QueryBuilder builder = DbManager.getDaoMaster(context).newSession().getEyeChartsBeanDao().queryBuilder();
			List<EyeChartsBean> beans = builder.orderDesc(EyeChartsBeanDao.Properties.Created_month).limit(limit).build().list();
			if (mView != null && mView.isActive()) {
				mView.getEyeChartsSuccee(beans);
			}
		}catch (Exception e){
			e.printStackTrace();
			if (mView != null && mView.isActive()) {
				mView.getEyeChartsFail("数据加载失败");
			}
		}
	}


	private void getEyeChartsNet(int limit){
		EyeDataManager.getInstance().getEyeTestCharts(SnUtils.getSN(),limit)
				.subscribe(new RxCallback<NewResponseImpl<ArrayList<EyeChartsBean>>>() {
					@Override
					public void onSuccess(NewResponseImpl<ArrayList<EyeChartsBean>> response) {
						if(mView != null && mView.isActive()){
							if(response.isSuccess()){
								mView.getEyeChartsSuccee(response.getData());
							}else{
								mView.getEyeChartsFail("数据获取失败");
							}
						}
					}

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

}
