package com.hw.nativeapp.httpnet.upgrade;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.hw.nativeapp.MApplication;
import com.hw.nativeapp.utils.FileUtils;
import com.hw.nativeapp.utils.LogUtils;
import com.hw.nativeapp.utils.StringUtils;
import com.hw.nativeapp.utils.ToastUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;

import java.io.File;

public class UpgradeHandler {

    public static final String TAG = UpgradeHandler.class.getName();

    private String downloadUrl;
    private String downloadLocalPath;
    private Context context;
    private UpgradeHandler.OnDownloadListener onDownloadListener;

    public UpgradeHandler(Context context , String downloadUrl){
        this.downloadUrl = downloadUrl;
        this.context = context;
    }

    public interface OnDownloadListener {
        void complate();
        void progress(int soFarBytes, int totalBytes);
    }

    public void setOnListener(UpgradeHandler.OnDownloadListener listener) {
        this.onDownloadListener = listener;
    }


    public void start(){
        if (StringUtils.isEmpty(this.downloadUrl)){
            ToastUtils.showLongToast(MApplication.getAppContext(), "下载地址为空");
        }
        this.downloadLocalPath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "tmpdir1" + File.separator +
                "download.apk";
//        this.downloadLocalPath = this.context.getExternalFilesDir(null).getPath() + File.separator + "tmpdir1" + File.separator +
//                "download.apk";
//        this.downloadLocalPath = Environment.getExternalStorageDirectory().getPath() + File.separator + "tmpdir1" + File.separator +
//                "download.apk";
        if (FileUtils.isFileExists(this.downloadLocalPath)){
            FileUtils.deleteFile(this.downloadLocalPath);
        }
        LogUtils.d("download", "下载地址 ---->" + this.downloadUrl );
        LogUtils.d("download", "存储路径 ---->" + this.downloadLocalPath );
        FileDownloader.getImpl().create(this.downloadUrl)
                .setPath(this.downloadLocalPath)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        LogUtils.d("download", "pending ---->");
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        LogUtils.d("download", "connected ---->");
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        LogUtils.d("download", "progress ---->" + soFarBytes + ":" + totalBytes);
                        onDownloadListener.progress(soFarBytes, totalBytes);
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                        LogUtils.d("download", "blockComplete ---->");
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                        LogUtils.d("download", "retry ---->");
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        LogUtils.d("download", "completed ---->");
                        onDownloadListener.complate();
                        installApk();
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        LogUtils.d("download", "paused ---->");
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        LogUtils.d("download", "error ---->");
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        LogUtils.d("download", "warn ---->");
                    }
                }).start();
    }

    private void installApk(){

        File apkFile = new File(this.downloadLocalPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.w(TAG, "版本大于 N ，开始使用 fileProvider 进行安装");
//            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    this.context
                    , this.context.getApplicationContext().getPackageName() + ".provider"
                    , apkFile);
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            Log.w(TAG, "正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        this.context.startActivity(intent);
    }
}
