package tech.starwin.mvp.presenter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.common.bean.PhotoListBean;
import com.google.gson.Gson;


import java.io.File;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import tech.starwin.LibConfig;
import tech.starwin.base.BasePresenter;
import tech.starwin.constants.TrackEvent;
import tech.starwin.impl.HttpObserver;
import tech.starwin.mvp.api.UploadApi;

import com.common.bean.BasicAck;
import com.common.bean.OcrResultBean;
import com.google.gson.JsonObject;

import tech.starwin.utils.LogUtils;
import tech.starwin.utils.LoginManager;
import tech.starwin.utils.MultipartBodyMaker;
import tech.starwin.utils.PreferencesManager;
import tech.starwin.utils.TrackEventHelper;
import tech.starwin.utils.context_utils.AppInfoUtils;

/**
 * Created by SiKang on 2018/9/25.
 */
public class UploadPresenter extends BasePresenter<UploadApi> {

    public UploadPresenter() {
        super(UploadApi.class);
    }

    /**
     * 身份证ocr识别
     */
    public void identityOcr(final String action, @NonNull File file) {
        handleRequest(apiService.identityOcr(MultipartBodyMaker.makeSimplePart("file", file), LoginManager.get().getToken()),
                new HttpObserver<OcrResultBean>() {
                    @Override
                    public void onStart() {
                        view.onHttpStart(action, true);
                    }

                    @Override
                    public void onSuccess(OcrResultBean data) {
                        TrackEventHelper.logEvent(TrackEvent.IDENTITY_INFO_SUBMIT);
                        OcrResultBean.KTP ktp = new Gson().fromJson(data.getData(), OcrResultBean.KTP.class);
                        if (ktp != null && ktp.getResult() != null) {
                            if (ktp.getResult().equals("PASS")) {
                                view.onHttpSuccess(action, ktp);
                            } else if (!TextUtils.isEmpty(ktp.getMessage())) {
                                view.onHttpError(action, ktp.getMessage());
                            }
                        } else if (!TextUtils.isEmpty(data.getMessage())) {
                            view.onHttpError(action, data.getMessage());
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        view.onHttpError(action, msg);
                    }

                    @Override
                    public void onFinish() {
                        view.onHttpFinish(action);
                    }
                });
    }


    /**
     * 上传依图 截取得帧图片
     */
    public void faceVerify(final String action, Context context, double amount, int day, long productId) {
        faceVerify(action, AppInfoUtils.getAndroidID(context), PreferencesManager.get().getVerificationData(), amount, day, productId, "yitu");
    }

    /**
     * 上传advance 活体图片
     */
    public void advanceFaceVerify(final String action, String androidId, String faceData, double amount, int day, long productId) {
        String livenessId = new Gson().fromJson(faceData, JsonObject.class).get("livenessId").toString().replace("\"", "");
        faceVerify(action, androidId, livenessId, amount, day, productId, "advance");
    }


    public void faceVerify(final String action, String androidId, String faceData, double amount, int day, long productId, String method) {
        TrackEventHelper.logEvent(TrackEvent.FACE_DETECTION);
        handleRequest(
                apiService.faceVerify(
                        "PAYDAY", amount, day, "D", null, null,
                        MultipartBodyMaker.makeSimplePart("delta", faceData),
                        androidId,
                        productId,
                        !TextUtils.isEmpty(LibConfig.TONGDUN_PARENT_KEY),
                        method,
                        LoginManager.get().getToken()
                ),
                new HttpObserver<BasicAck>() {
                    @Override
                    public void onStart() {
                        view.onHttpStart(action, true);
                    }

                    @Override
                    public void onSuccess(BasicAck data) {
                        TrackEventHelper.logEvent(TrackEvent.FACE_DETECTION_SUCCESS);
                        view.onHttpSuccess(action, data);
                    }

                    @Override
                    public void onError(int code, String msg) {
                        view.onHttpError(action, msg);
                    }

                    @Override
                    public void onFinish() {
                        view.onHttpFinish(action);
                    }
                });
    }

    /**
     * 无活体SDK 时，后台设置活体检查次数，这里连续请求若干次，直到通过
     */
    public void faceVerifyWithoutSDK(final String action, Context context, double amount, int day, long productId) {
        Observable observable = Observable.fromArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
                .flatMap((Function<Integer, ObservableSource<BasicAck>>) integer ->
                        apiService.faceVerify("PAYDAY", amount, day, "D", null, null,
                                MultipartBodyMaker.makeSimplePart("delta", "null"), AppInfoUtils.getAndroidID(context), productId,
                                !TextUtils.isEmpty(LibConfig.TONGDUN_PARENT_KEY), "yitu", LoginManager.get().getToken()
                        ).onErrorReturn(throwable -> new BasicAck()))
                .filter(basicAck -> basicAck != null && basicAck.getData() != null)
                .take(1);


        handleRequest(observable, new HttpObserver<BasicAck>() {
            @Override
            public void onStart() {
                view.onHttpStart(action, true);
            }

            @Override
            public void onSuccess(BasicAck data) {
                TrackEventHelper.logEvent(TrackEvent.FACE_DETECTION_SUCCESS);
                view.onHttpSuccess(action, data);
            }

            @Override
            public void onError(int code, String msg) {
                view.onHttpError(action, msg);
            }

            @Override
            public void onFinish() {
                view.onHttpFinish(action);
            }
        });
    }


    /**
     * 上传fireBaseMessing Token
     */
    public void uploadFirebaseToken(String action, String token) {
        if (!TextUtils.isEmpty(token)) {
            handleRequest(action, apiService.uploadFirebaseToken(token));
        }
    }


    /**
     * 上传其他证件照
     */
    public void uploadOtherPhoto(String action, File file, List<PhotoListBean.Photo> photoList) {
        int index = 0;
        while (true) {
            boolean isEffective = true;
            for (PhotoListBean.Photo photo : photoList) {
                if (index == photo.getIndex()) {
                    isEffective = false;
                }
            }
            if (isEffective) {
                break;
            } else {
                index++;
            }
        }
        handleRequest(action, apiService.uploadOtherPhoto(MultipartBodyMaker.makeSimplePart("file", file), "EXTRA", index, "ADD"));
    }

    /**
     * 删除其他证件照
     */
    public void deleteOtherPhoto(String action, int photoIndex) {
        handleRequest(action, apiService.uploadOtherPhoto(MultipartBodyMaker.makeSimplePart("file", "null"), "EXTRA", photoIndex, "DELETE"));
    }


}
