package com.chexiang.myhome.utils;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.util.Patterns;
import android.widget.Toast;

import java.io.File;

/**
 * Created by Administrator on 2017/5/15.
 */

public class UpdateUtils {
    private static boolean canDownloadState(Context ctx) {
        try {
            int state = ctx.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void checkUpdate(final Context ctx, final String subAppName, final String url) {
        new Thread() {
            @Override
            public void run() {

                if (canDownloadState(ctx)) {
                    checkDownload(ctx, subAppName, url);
                } else {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(url);
                    intent.setData(content_url);
                    ctx.startActivity(intent);
                }
            }
        }.start();
    }

    private static void checkDownload(Context context, String title, String downloadUrl) {
        if (Patterns.WEB_URL.matcher(downloadUrl).matches()) {
            long downloadId = downloadApk( context, downloadUrl, title);
            if(downloadId==0)
                return;
        }
    }


    private static long downloadApk( Context context, String url, String title) {
        try{
            Uri downloadUri = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(downloadUri);
            String apkName = title + ".apk";
            //
            File file = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/" + apkName);
            if (file != null && file.exists()) {
                file.delete();
            }
            request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS,
                    apkName);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setVisibleInDownloadsUi(true);
            request.setTitle(title);
            DownloadManager mDownloadManager = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
            return mDownloadManager.enqueue(request);
        }catch (Exception e){
            ToastUtil.showToast(context,"下载地址错误,请前往官网下载");
        }
        return 0;
    }

    public static boolean checkVersionName(Context context, String nowVersionName) {
        try {
            String versionName = getVersion(context);
            String[] version = versionName.split("\\.");
            String[] nowVersion = nowVersionName.split("\\.");
            for (int i = 0; i < version.length; i++) {
                if (Integer.valueOf(version[i]) < Integer.valueOf(nowVersion[i])) return true;
            }
            if (version.length < nowVersion.length) return true;
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String getVersion(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void update(final Context context, final boolean noToast) {
        //检查更新

    }
}