package com.emato.ich.update;


import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.emato.ich.api.ICSPClient;
import com.emato.ich.utils.BaseUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class APKUpdateDownload {

    private static final String TAG = APKUpdateDownload.class.getName();
    private static final String destFileDir = "res/apk/";
    private static String destFileName = "ich-android.apk";
    private static final APKUpdateDownload INSTANCE = APKUpdateDownloadInnerClass.apkUpdateDownload;

    private APKUpdateDownload(){}

    public static APKUpdateDownload getInstance(){
        return INSTANCE;
    }

    static class APKUpdateDownloadInnerClass{
        private static final APKUpdateDownload apkUpdateDownload = new APKUpdateDownload();
    }

    public void downloadAPK(Activity activity, Context context, String apk_url) {
        OnDownloadListener listener = new OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                Log.i(TAG, "onDownloadSuccess: 下载完成! ");
                // 文件路径
                String absolutePath = file.getAbsolutePath();
                // 需要自动安装并重启
                APKAutoUpdate.installApk(context, absolutePath, new OnInstallListener() {
                    @Override
                    public void onInstallException(Exception e) {
                        Log.e(TAG, "onInstallException: 安装出现异常! " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), e);
                    }

                    @Override
                    public void onInstallSuccess() {
                        // TODO 重启应用 重启失败? 一直重启?
                        PackageManagerCompat.restartApp(context);
                    }
                });
            }

            @Override
            public void onDownloading(int progress) {
                Log.i(TAG, "onDownloading: 下载进度========>" + progress + "%");
            }

            @Override
            public void onDownloadFailed(Exception e) {
                Log.e(TAG, "onDownloadFailed: 下载失败! 原因==> ", e);
            }
        };
        ICSPClient.download(apk_url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                listener.onDownloadFailed(e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;

                //储存下载文件的目录
                File dir = new File(context.getFilesDir().getAbsolutePath() + "/" +destFileDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
//                destFileName = apk_url.substring(apk_url.lastIndexOf('/'), apk_url.length() - 1);
                File file = new File(dir, destFileName);

                try {

                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //下载中更新进度条
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    //下载完成
                    listener.onDownloadSuccess(file);
                } catch (Exception e) {
                    listener.onDownloadFailed(e);
                }finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {

                    }

                }
            }
        }, listener);
    }

}
