package com.emato.ich.update;

import android.util.Log;

import androidx.annotation.NonNull;

import com.emato.ich.api.ICSPClient;
import com.emato.ich.utils.BaseUtils;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.proxy.IUpdateHttpService;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UpdateService implements IUpdateHttpService {

    private static final String TAG = UpdateService.class.getName();
    private static final OkHttpClient client = new OkHttpClient.Builder().callTimeout(10, TimeUnit.MINUTES).readTimeout(10, TimeUnit.MINUTES).build();

    @Override
    public void asyncGet(@NonNull @NotNull String url, @NonNull @NotNull Map<String, Object> params, @NonNull @NotNull Callback callBack) {
        OkHttpUtils.get()
                .url(url)
                .addParams("clientId", BaseUtils.getClientId())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        callBack.onError(e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        callBack.onSuccess(response);
                    }
                });
    }

    private Map<String, String> transform(Map<String, Object> params) {
        Map<String, String> map = new HashMap<>();
        params.keySet().forEach(key -> {
            map.put(key, String.valueOf(params.get(key)));
        });
        map.put("clientId", BaseUtils.getClientId());
        return map;
    }

    @Override
    public void asyncPost(@NonNull @NotNull String url, @NonNull @NotNull Map<String, Object> params, @NonNull @NotNull Callback callBack) {

        OkHttpUtils.post()
//                .params(transform(params))
                .url(url)
                .addParams("clientId", BaseUtils.getClientId())
                // .addParams("clientId", "285F18D92D0B6568")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        callBack.onError(e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //response = "{\"Code\":0,\"Msg\":\"\",\"UpdateStatus\":2,\"VersionCode\":3,\"VersionName\":\"1.0.2\",\"ModifyContent\":\"1、优化api接口。\\r\\n2、添加使用demo演示。\\r\\n3、新增自定义更新服务API接口。\\r\\n4、优化更新提示界面。\",\"DownloadUrl\":\"http://icsp-api.ds-bay.com/profile/app-release.apk\",\"ApkSize\":10759906,\"ApkMd5\":\"3452dfgdg\"}";
                        callBack.onSuccess(response);
                    }
                });

    }

    @Override
    public void download(@NonNull @NotNull String url, @NonNull @NotNull String path, @NonNull @NotNull String fileName, @NonNull @NotNull DownloadCallback callback) {

        OkHttpUtils.initClient(client);
        OkHttpUtils.get()
                .url(url)
                .tag(url)
                .build()
                .execute(new FileCallBack(path, fileName) {
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        callback.onProgress(progress, total);
                        Log.i(TAG, "inProgress: ====================================>progress完成! ===>" + progress);
                    }

                    @Override
                    public void onBefore(Request request, int id) {
                        callback.onStart();
                        Log.i(TAG, "onBefore: ====================================>Before 完成! ");
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        callback.onError(e);
                        Log.e(TAG, "onError: ====================================>下载出现异常! ", e);
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        callback.onSuccess(response);
                        Log.i(TAG, "onResponse: ====================================>下载完成! 等待安装....");
                    }
                });

    }

    @Override
    public void cancelDownload(@NonNull @NotNull String url) {

    }
}
