package org.fouram.core.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class FileUtil {

	public static void main(String[] args) {
		saveUrlAs("http://f.buka.tv/1c26eed24ccf4f17841c689b8c1cec7f.flv", "e://1.flv");
	}

	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {
			return false;
		}
		if (!destDirName.endsWith(File.separator)) {
			destDirName = destDirName + File.separator;
		}

		if (dir.mkdirs()) {
			return true;
		}
		return false;
	}

	public static void delFile(String filePathAndName) {
		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myDelFile = new File(filePath);
			myDelFile.delete();
		} catch (Exception e) {
			// System.out.println("删除文件操作出错");
			LoggerUtil.error(e);
		}
	}

	@SuppressWarnings("resource")
	public static byte[] getContent(String filePath) throws IOException {
		File file = new File(filePath);
		long fileSize = file.length();
		if (fileSize > 2147483647L) {
			// System.out.println("file too big...");
			return null;
		}
		FileInputStream fi = new FileInputStream(file);
		byte[] buffer = new byte[(int) fileSize];
		int offset = 0;
		int numRead = 0;
		while ((offset < buffer.length) && ((numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0)) {
			offset += numRead;
		}

		if (offset != buffer.length) {
			throw new IOException("Could not completely read file " + file.getName());
		}
		fi.close();
		return buffer;
	}

	public static byte[] toByteArray(String filePath) throws IOException {
		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException(filePath);
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			return bos.toByteArray();
		} catch (IOException e) {
			LoggerUtil.error(e);
			throw e;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				LoggerUtil.error(e);
			}
			bos.close();
		}
	}

	public static byte[] toByteArray2(String filePath) throws IOException {
		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException(filePath);
		}

		FileChannel channel = null;
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(f);
			channel = fs.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
			while (channel.read(byteBuffer) > 0)
				;
			return byteBuffer.array();
		} catch (IOException e) {
			LoggerUtil.error(e);
			throw e;
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				LoggerUtil.error(e);
			}
			try {
				fs.close();
			} catch (IOException e) {
				LoggerUtil.error(e);
			}
		}
	}

	public static byte[] toByteArray3(String filePath) throws IOException {
		FileChannel fc = null;
		RandomAccessFile rf = null;
		try {
			rf = new RandomAccessFile(filePath, "r");
			fc = rf.getChannel();
			MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0L, fc.size()).load();

			byte[] result = new byte[(int) fc.size()];
			if (byteBuffer.remaining() > 0) {
				byteBuffer.get(result, 0, byteBuffer.remaining());
			}
			return result;
		} catch (IOException e) {
			LoggerUtil.error(e);
			throw e;
		} finally {
			try {
				rf.close();
				fc.close();
			} catch (IOException e) {
				LoggerUtil.error(e);
			}
		}
	}

	public static boolean saveUrlAs(String fileUrl, String localFilePath) {
		// 此方法只能用户HTTP协议
		try {
			File file = new File(localFilePath);
			if (!file.exists()) {
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				file.createNewFile();
			}

			URL url = new URL(fileUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			DataInputStream in = new DataInputStream(connection.getInputStream());
			DataOutputStream out = new DataOutputStream(new FileOutputStream(localFilePath));
			byte[] buffer = new byte[4096];
			int count = 0;
			while ((count = in.read(buffer)) > 0) {
				out.write(buffer, 0, count);
			}
			out.close();
			in.close();
			return true;
		} catch (Exception e) {
			LoggerUtil.error(e);
			return false;
		}
	}

	public static void textToFile(String strFilename, String strBuffer) {
		try {
			// 创建文件对象
			File fileText = new File(strFilename);
			if (!fileText.exists()) {
				fileText.getParentFile().mkdirs();
			}
			// 向文件写入对象写入信息
			FileWriter fileWriter = new FileWriter(fileText);
			// 写文件
			fileWriter.write(strBuffer);
			// 关闭
			fileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
