package com.oo.eye.mvp.presenter;

import android.content.Context;

import com.oo.eye.EyeConfig;
import com.oo.eye.bean.EyeChartsBean;
import com.oo.eye.bean.EyeHistroyBean;
import com.oo.eye.db.DbManager;
import com.oo.eye.mvp.contract.EyeTestContract;
import com.oo.eye.net.EyeDataManager;
import com.oo.seex.netlibrary.net.response.NewResponseImpl;
import com.oo.seex.netlibrary.net.response.RxCallback;

import java.text.SimpleDateFormat;
import java.util.Date;

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

public class EyeTestPresenter implements EyeTestContract.Presenter {

    private EyeTestContract.View mView;

    public EyeTestPresenter(EyeTestContract.View view) {
        this.mView = view;
    }

    public void postEyeTestData(Context context, String sn, double leftEye, double rightEye,
								int leftLine, int rightLine) {
        if (EyeConfig.getInstance().isNetData()) {
            EyeDataManager.getInstance()
                    .postEyeTestData(sn, String.valueOf(leftEye), String.valueOf(rightEye), String.valueOf(leftLine), String.valueOf(rightLine))
                    .subscribe(new RxCallback<NewResponseImpl<String>>() {
                        @Override
                        public void onSuccess(NewResponseImpl<String> stringEyeResponse) {
                            if (mView != null && mView.isActive())
                                mView.postEyeTestDataSuccee();
                        }

                        @Override
                        public void onError(int errorCode, String errorMessage) {
                            if (mView != null && mView.isActive())
                                mView.postEyeTestDataFail(errorMessage);
                        }
                    });
        } else {
            Date date = new Date();
            EyeHistroyBean histroyBean = new EyeHistroyBean();
            histroyBean.setLeft_eye(leftEye);
            histroyBean.setRight_eye(rightEye);
            histroyBean.setLeft_line(leftLine);
            histroyBean.setRight_line(rightLine);
            histroyBean.setCreated_time(date.getTime());
            histroyBean.setType(2);
            DbManager.getDaoMaster(context).newSession().insert(histroyBean);
            EyeChartsBean chartsBean = new EyeChartsBean();
            chartsBean.setLeft_eye(leftEye);
            chartsBean.setRight_eye(rightEye);
            chartsBean.setType(2);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            chartsBean.setCreated_month(simpleDateFormat.format(date));
            DbManager.getDaoMaster(context).newSession().insertOrReplace(chartsBean);
            if (mView != null) {
                mView.postEyeTestDataSuccee();
            }
        }
    }
}
