package util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;

import activity.UpdateAppActivity;
import teprinciple.updateapputils.R;
import view.DownloadDialog;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2019/2/16
 * 修订历史：2019/2/16
 * 描述：
 */
public class DownloadAppUtils {
    private static final String TAG = DownloadAppUtils.class.getSimpleName();
    public static String downloadUpdateApkFilePath;//下载更新Apk 文件路径

    public static String APK = "Download";//安装包目录放在系统目录
    public static final String APK_PATH = File.separator + APK + File.separator;

    private Context context;

    /**
     * 通过浏览器下载APK包
     */
    public static void downloadForWebView(Context context, String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    public static void download(final Activity context, String url, final String serverVersionName, ProgressBar progressBar, TextView content) {

        String packageName = context.getPackageName();
        String filePath = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//外部存储卡
            filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + APK_PATH;
        } else {
            Log.i(TAG, "没有SD卡");
            return;
        }

        String apkLocalPath = filePath + "GsAndroid" + "_" + serverVersionName + ".apk";

        deleteOldGsAndroidApkFiles(new File(filePath));

        downloadUpdateApkFilePath = apkLocalPath;

        FileDownloader.setup(context);

        BaseDownloadTask downloadTask = FileDownloader.getImpl().create(url);

        downloadTask.setPath(apkLocalPath);
        downloadTask.setListener(new FileDownloadLargeFileListener() {

            @Override
            protected void started(BaseDownloadTask task) {
                content.setText("");
            }

            @Override
            protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {

            }

            @Override
            protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                int pro = (int) (soFarBytes * 100.0 / totalBytes);
                progressBar.setProgress(pro);
                content.setText(pro + "%");

                send(context, pro, serverVersionName);
            }

            @Override
            protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {
            }

            @Override
            protected void completed(BaseDownloadTask task) {
                context.finish();
                send(context, 100, serverVersionName);
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                //Toast.makeText(context, "下载出错", Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void warn(BaseDownloadTask task) {
            }
        }).start();
    }

    /**
     * 删除目录下旧GsaAndroid Apk
     *
     * @param file
     */
    private static void deleteOldGsAndroidApkFiles(File file) {
        File files[] = file.listFiles();
        if (files != null)
            for (File f : files) {
                if (f.getName().contains("GsAndroid") && f.exists()) {// 判断是否存在  
                    deleteOldGsAndroidApkFiles(f);
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                }
            }
    }


    private static void send(Context context, int progress, String serverVersionName) {
        Intent intent = new Intent("teprinciple.update");
        intent.putExtra("progress", progress);
        intent.putExtra("title", serverVersionName);
        context.sendBroadcast(intent);
    }
}
