package org.apache.fyldemo;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.widget.Toast;

/**
 * 最新添加
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * This class echoes a string called from JavaScript.
 */
public class downloadandunzipandsave extends CordovaPlugin {
	// 需要下载资源的url地址
	private String urlStr = "http://47.52.30.102:8080/www/www.zip";
	// 下载资源保存路径
	private String path;
	// 下载资源保存下来的文件名
	private String fileName = "downFile.zip";
	// 下载资源的大小
	private int downSize;
	// 下载的文件
	private File localFile;
	//文件解压保存路径
	private String targetDir;

	@Override
	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		if ("downloadAndunzip".equals(action)) {
			//Toast.makeText(cordova.getActivity(), "你成功了...", Toast.LENGTH_SHORT).show();
			/**
			 * 最新添加
			 */
			
			path = this.cordova.getActivity().getApplication().getCacheDir().toString();
			httpUrlConnectionDown();
			callbackContext.success("success");
			return true;
		}
		callbackContext.error("error");
		return false;
	}

	/**
	 * 最新添加
	 */
	// 该方法用来实现获取资源大小，同时创建本地的资源存储地址
	public void httpUrlConnectionDown() {
		new Thread() {
			@Override
			public void run() {
				super.run();
				try {
					Log.i("test", "httpurlConnetionDown>>>>>>>");
					URL url = new URL(urlStr);
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					// 设置请求服务器请求超时时间
					conn.setConnectTimeout(14 * 1000);
					conn.setRequestMethod("GET");
					conn.setRequestProperty("Accept",
							"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
					conn.setRequestProperty("Accept-Language", "zh-CN");
					conn.setRequestProperty("Referer", urlStr);
					conn.setRequestProperty("Charset", "UTF-8");
					conn.setRequestProperty("User-Agent",
							"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
					conn.setRequestProperty("Connection", "Keep-Alive");
					conn.connect();
					//从url获取数据流
					InputStream inputStream = conn.getInputStream();

					if (conn.getResponseCode() == 200) {
						downSize = conn.getContentLength();
						Log.i("test", ",,,,,," + downSize);
						if (downSize <= 0) {
							Log.i("Test", "文件为空");
							throw new RuntimeException("the file that you download has a wrong size ... ");
						}
						File fileDir = new File(path);
						if (!fileDir.exists()) {
							fileDir.mkdirs();
						}
						localFile = new File(fileDir, fileName);
						RandomAccessFile raf = new RandomAccessFile(localFile, "rw");
						int lengths = 0;
						byte[] bt = new byte[1024];
						RandomAccessFile rafile = new RandomAccessFile(localFile, "rwd");
						while ((lengths = inputStream.read(bt)) != -1) {
							rafile.write(bt, 0, lengths);
						}
						raf.close();
						inputStream.close();
						Log.i("Test", "需要下载的文件大小为:" + downSize + ",存储位置为:" + path + "/" + fileName);
						//调用方法将压缩文件保存到相应的目录下
						Unzip(localFile.toString(), path);
					} else {
						throw new RuntimeException("url that you conneted has error ...");
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
		
	}

	/**
	 * 对下载下来的文件进行解压(第一个参数代表压缩包路径，第二个参数代表你所要解压的路径)
	 */

	private boolean Unzip(String zipFile, String targetDir) {
		ZipFile zfile = null;
		try {
			zfile = new ZipFile(zipFile);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		//枚举接口，作用类似于iterator
		Enumeration zList = zfile.entries();
		ZipEntry ze = null;
		byte[] buf = new byte[1024];
		/**
		 * 循环遍历，将zip文件夹下的文件目录全部生成
		 */
		while (zList.hasMoreElements()) {
			ze = (ZipEntry) zList.nextElement();
			// 列举的压缩文件里面的各个文件，判断是否为目录
			if (ze.isDirectory()) {
				String dirstr = targetDir + ze.getName();
				dirstr.trim();
				File f = new File(dirstr);
				if (!f.exists()) {
					f.mkdir();
				}
				//跳出本次循环，执行下一次循环
				continue;
			}

			OutputStream os = null;
			FileOutputStream fos = null;
			// ze.getName()会返回 script/start.script这样的，是为了返回实体的File
			File realFile = getReallyFileName(targetDir, ze.getName());
			try {
				fos = new FileOutputStream(realFile);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return false;
			}
			os = new BufferedOutputStream(fos);
			InputStream is = null;
			try {
				is = new BufferedInputStream(zfile.getInputStream(ze));
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			int readLen = 0;
			//进行一些内容复制操作
			try {
				while ((readLen = is.read(buf, 0, 1024)) != -1) {
					os.write(buf, 0, readLen);
				}
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		try {
			zfile.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		Log.i("test", "解压完成");
		return true;
	}

	/**
	 * 给定根目录，返回一个相对路径所对应的实际文件名.
	 *
	 * @param baseDir     指定根目录
	 * @param absFileName 相对路径名，来自于ZipEntry中的name
	 * @return java.io.File 实际的文件
	 */
	public static File getReallyFileName(String baseDir, String absFileName) {
		//使用String.split("")方法将字符创划分为一个数组，取出第一个数值，变相的相当于截取
		String[] dirs = absFileName.split("/");
		File ret = new File(baseDir);
		String substr = null;

		if (dirs.length > 1) {
			for (int i = 0; i < dirs.length - 1; i++) {
				substr = dirs[i];
				ret = new File(ret, substr);
			}

			if (!ret.exists())
				ret.mkdirs();
			substr = dirs[dirs.length - 1];
			ret = new File(ret, substr);
			return ret;
		} else {
			ret = new File(ret, absFileName);
		}
		return ret;
	}

}

