package com.gh.common.util;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.os.StrictMode;

import org.apache.http.HttpStatus;
import org.json.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * 
 * @author guanchao wen
 * @email shuwoom.wgc@gmail.com
 * @modify hzh 2016/03/16
 * @update 2015-7-29下午2:26:02
 */
public class FileUtils {

	private final static String TEST_FILE_NAME = System.currentTimeMillis() + ".log";

	public static String getDownloadDir(Context context) {
		String dir = null;
		if (isMounted()) {
			String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
			dir = checkDir(baseDir + File.separator + "gh-download");
			File file = new File(dir + File.separator + TEST_FILE_NAME);
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
					//cannot create file
					Utils.log("cannot create file");
					dir = null;
				}
			}
		}
		if (dir == null) {
			String baseDir = context.getFilesDir().getAbsolutePath();
			dir = checkDir(baseDir + File.separator + "gh-download");
		}
		return dir;
	}

	public static String getDownloadPath(Context context, String name) {
		return getDownloadDir(context) + File.separator + name;
	}
	
	public static String getLogPath(Context context, String name) {
		return checkDir(getDir(context, "log")) + File.separator + name;
	}

	public static String getPlatformPicDir(Context context) {
		return checkDir(getDir(context, "PlatformPic"));
	}

	public static String getAdPicDir(Context context) {
		return checkDir(getDir(context, "AdPic"));
	}

	public static String getPicPath(Context context, String name) {
		return checkDir(getDir(context, "Pic")) + File.separator + name;
	}
	
	private static String checkDir(String dir) {
		File directory = new File(dir);
		if (!directory.exists() || !directory.isDirectory()) {
			directory.mkdirs();
		}
		return dir;
	}

	public static void deleteFile(String savePath) {
		File file = new File(savePath);
		if (file.exists()) {
			file.delete();
		}
	}

	public static boolean isEmptyFile(String path) {
		File file = new File(path);
		if (file.exists() && file.length() != 0) {
			return false;
		}
		return true;
	}
	
	public static void checkDirExists(String dirName) {
		File file = Environment.getExternalStorageDirectory();
		if (file.isDirectory()) {
			File[] fs = file.listFiles();
			for (int i = 0; i < fs.length; i++) {
				if (fs[i].isDirectory()
						&& fs[i].getName().equalsIgnoreCase(dirName)
						&& !fs[i].getName().equals(dirName)) {
					fs[i].delete();
					break;
				}
			}
		}
	}

	public static boolean isMounted() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	public static String getDir(Context context, String dir) {
		if (isMounted()) {
			// /storage/emulated/0/Android/data/包名/files
			File file = context.getExternalFilesDir(null);
			if (file != null) {
				return file.getAbsolutePath() + File.separator + dir;
			}
		}
		// /data/data/包名/files
		return context.getFilesDir().getAbsolutePath() + File.separator + dir;
	}

	/*
	 * 返回剩余空间 单位MB
	 */
	@SuppressWarnings("deprecation")
	public static float getFreeSpaceByPath(String path) {
		StatFs statfs = new StatFs(path);
		long blockSize = statfs.getBlockSize();
		long availableBlocks = statfs.getAvailableBlocks();

		return availableBlocks * blockSize / 1024f / 1024f;
	}

	public static String isCanDownload(String size) {
		String msg = null;
		String packageSizeStr = "";
		for (int i = 0; i < size.length(); i++) {
			if ((size.charAt(i) >= 48 && size.charAt(i) <= 57) || size.charAt(i) == 46) {
				packageSizeStr += size.charAt(i);
			}
		}
		float packageSize = 0;
		if (packageSizeStr.length() != 0) {
			packageSize = Float.valueOf(packageSizeStr);
		}
		float freeSpace = getFreeSpaceByPath(Environment
				.getExternalStorageDirectory().getAbsolutePath());
		if (freeSpace < packageSize) {
			msg = "手机存储空间不足，无法进行下载！";
		}
		return msg;
	}

	// 下载文件
	public static int downloadFile(String url, String savePath)
			throws IOException {
		DataInputStream dis = null;
		FileOutputStream fos = null;
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(5 * 1000);
			connection.setReadTimeout(5 * 1000);
			connection.connect();
			int code = connection.getResponseCode();
			if (code == 200) {
				dis = new DataInputStream(connection.getInputStream());
				File file = new File(savePath);
				if (file.exists()) {
					file.delete();
				}
				file.createNewFile();
				fos = new FileOutputStream(file);
				byte[] buffer = new byte[1024];
				int len;
				while ((len = dis.read(buffer)) != -1) {
					fos.write(buffer, 0, len);
				}
				fos.flush();
				fos.close();
				dis.close();
			}
			return code;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			if (fos != null) {
				fos.close();
			}
			if (dis != null) {
				dis.close();
			}
		}
	}

	// 上传文件
	public static JSONObject uploadFile(String url, String filePath, String token) {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = UUID.randomUUID().toString().replaceAll("-", "")
				.substring(0, 16);
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(url)
					.openConnection();
			/*
			 * Output to the connection. Default is false, set to true because
			 * post method must write something to the connection
			 */
			connection.setDoOutput(true);
			// Read from the connection. Default is true.
			connection.setDoInput(true);
			// Post cannot use caches
			connection.setUseCaches(false);
			// Set the post method. Default is GET
			connection.setRequestMethod("POST");
			// 设置请求属性
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			if (token != null) {
				connection.setRequestProperty("TOKEN", token);
			}
			// 设置StrictMode 否则HTTPURLConnection连接失败，因为这是在主进程中进行网络连接
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.detectDiskReads().detectDiskWrites().detectNetwork()
					.penaltyLog().build());
			File file = new File(filePath);
			if (file.exists()) {
				Utils.log("name = " + file.getName());
				Utils.log("length = " + file.length());
			}
			// 设置DataOutputStream，getOutputStream中默认调用connect()
			DataOutputStream dos = new DataOutputStream(
					connection.getOutputStream()); // output
			// to the connection
			dos.writeBytes(twoHyphens + boundary + end);
			dos.writeBytes("Content-Disposition: form-data; "
					+ "name=\"Filedata\";filename=\"" + file.getName() + "\""
					+ end);
			dos.writeBytes(end);
			// 取得文件的FileInputStream
			FileInputStream fStream = new FileInputStream(file);
			// 设置每次写入8192bytes
			int bufferSize = 8192;
			byte[] buffer = new byte[bufferSize]; // 8k
			int length = -1;
			// 从文件读取数据至缓冲区
			while ((length = fStream.read(buffer)) != -1) {
				// 将资料写入DataOutputStream中
				dos.write(buffer, 0, length);
			}
			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			// 关闭流，写入的东西自动生成Http正文
			fStream.close();
			// 关闭DataOutputStream
			dos.close();

			// 从返回的输入流读取响应信息
			InputStream is = connection.getInputStream(); // input from the connection

			// 正式建立HTTP连接
			Utils.log("con.getResponseCode() = " + connection.getResponseCode());
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			// 显示网页响应内容
			Utils.log("content = " + b.toString().trim());

			// {"icon":"http:\/\/gh-test-1.oss-cn-qingdao.aliyuncs.com\/pic\/57e4f4d58a3200042d29492f.jpg"}
			if (connection.getResponseCode() == HttpStatus.SC_OK) {
				JSONObject response = new JSONObject(b.toString().trim());
				response.put("statusCode", HttpStatus.SC_OK);
				return response;
			} else if (connection.getResponseCode() == HttpStatus.SC_FORBIDDEN) {
				JSONObject response = new JSONObject(b.toString().trim());
				response.put("statusCode", HttpStatus.SC_FORBIDDEN);
				return response;
			}
		} catch (Exception e) {
			// 显示异常信息
			Utils.log("Fail:" + e);
		}
		return null;
	}

}
