package cn.net.caoyao.cpzshandset.service.apkupdate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.util.Log;

public class DownloadManager {
	private static String downLoadFile = Environment
			.getExternalStorageDirectory() + "/CpzsCommonHandset/";
	/**
	 * 下载文件到sdcard
	 * 
	 * @param path
	 *            下载路径
	 * @return
	 * @throws Exception
	 */
	static String currentDate="";
	public static boolean download(String path, ProgressDialog mPd)

			throws Exception {
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		currentDate = simpleDateFormat.format(date);
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == 200) {
			mPd.setMax(conn.getContentLength());
			InputStream is = conn.getInputStream();
			Log.i("下载路径", downLoadFile);
			File f = new File(downLoadFile);
			if (!f.exists()) {
				f.mkdir();
			}
	
			File file = new File(downLoadFile+"tongyongban"+"("+currentDate+")"+".apk");
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			int count = 0;
			while ((len = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
				count = count + len;
				mPd.setProgress(count);
			}
			is.close();
			fos.close();
			return true;
		}
		return false;
	}

	// 得到文件名称
	public static String getFileName(String path) {
		return path.substring(path.lastIndexOf("/") + 1);
	}

	/**
	 * 自动安装新apk
	 */
	public static void installApk(Context context, UpdateInfoEntity updateInfo) {
//		Intent intent = new Intent();
//		intent.setAction(Intent.ACTION_VIEW);
//		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		String name = DownloadManager.getFileName(updateInfo.getUrl());
//		File file = new File(downLoadFile, name);
//		intent.setDataAndType(Uri.fromFile(file),
//				"application/vnd.android.package-archive");
//		context.startActivity(intent);
	
		String name = DownloadManager.getFileName(updateInfo.getUrl());
		   File file = new File(downLoadFile+"tongyongban"+"("+currentDate+")"+".apk");
	        Log.i("showfile",file.toString());
	        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) {//判读版本是否在7.0以上
	            Uri apkUri = FileProvider.getUriForFile(context, "cn.net.caoyao.cpzshandset.pro.fileprovider", file);
	            Intent install = new Intent(Intent.ACTION_VIEW);
	            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
	                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
	            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
	            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
	            context.startActivity(install);
	        }else {
	            Intent intent = new Intent(Intent.ACTION_VIEW);
	            intent.setDataAndType(Uri.parse("file://"+file), "application/vnd.android.package-archive");
	            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	            context.startActivity(intent);
	        }
//	    	((Activity) context).overridePendingTransition(R.anim.enter_default, R.anim.exit_default);
	}
}
