package com.mogo.cloud.tanlu.core;

import android.content.Context;

import com.google.gson.Gson;
import com.mogo.cloud.network.BaseData;
import com.mogo.cloud.network.NetConstants;
import com.mogo.cloud.network.RetrofitFactory;
import com.mogo.cloud.passport.MoGoAiCloudClient;
import com.mogo.cloud.tanlu.api.ITanluUploadCallback;
import com.mogo.cloud.tanlu.bean.InformationBody;
import com.mogo.cloud.tanlu.bean.UploadResult;
import com.mogo.cloud.tanlu.constant.HttpConstant;
import com.mogo.cloud.tanlu.net.TanluApiService;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author lixiaopeng
 * @description
 * @since 2021/1/21
 */
public class UploadManager {
    private static UploadManager sInstance;
    private Context mContext;
    private TanluApiService apiService;


    private UploadManager(Context context) {
        mContext = context;
    }

    public static UploadManager getInstance(Context context) {
        if (sInstance == null) {
            synchronized (UploadManager.class) {
                sInstance = new UploadManager(context);
            }
        }

        return sInstance;
    }

    public void init() {
        apiService = RetrofitFactory.INSTANCE.getInstance(NetConstants.DEVA_HOST)
                .create(TanluApiService.class);
    }

    /**
     * @param informationBody
     * @param callback
     */
    public void loadUpload(InformationBody informationBody, ITanluUploadCallback callback) {
        Gson gson = new Gson();
        Map<String, String> map = new HashMap<>();
        map.put("sn", MoGoAiCloudClient.getInstance().getAiCloudClientConfig().getSn());
        map.put("data", gson.toJson(informationBody));
        apiService.uploadInformation(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseData<UploadResult>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseData<UploadResult> result) {
                        callback.onSuccess(result);
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback.onError(e);
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

}
