package com.bcxin.utils;

import cn.hutool.core.util.StrUtil;
import com.google.common.io.Files;
import lombok.Data;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * <p>
 * 
 * </p>
 *
 * @author 罗鹏
 * @date 2018/3/13
 */
@Data
public class BcxinFileUtil {

	private final static String SIM_TEXT = "txt,html,xml,java,properties,sql,js,md,json,conf,ini,vue,php,py,bat,gitignore,log,htm,mp3,mp4,css,cnf";

	/**
	 * 根据 url 下载
	 *
	 * @param urlStr
	 //* @param fileName
	 //* @param savePath
	 * @return
	 */
	public static void download(String urlStr, File localFile) {
		FileOutputStream fos = null;
		InputStream inputStream = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//设置超时间为10秒
			conn.setConnectTimeout(10 * 1000);
			//防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			//得到输入流
			inputStream = conn.getInputStream();
			//获取自己数组
			byte[] getData = readInputStream(inputStream);
			//文件保存位置
			//File saveDir = new File(savePath);
			//if (!saveDir.exists()) {
			//	saveDir.mkdirs();
			//}
			//File file = new File(saveDir + File.separator + fileName);
			fos = new FileOutputStream(localFile);
			fos.write(getData);

			//String filePath = saveDir + "/" + fileName;
			//return filePath;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//return null;
	}

	private static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

	/**
	 * 处理文件夹路径，并根据文件夹路径创建文件夹
	 * @param paths
	 * @return
	 */
	public static String appendFolderPath(String[] paths){
		StringBuilder sb = new StringBuilder();
		for (String path:paths) {
			if (sb.length()==0) {
				sb.append(path);
			} else {
				if (StrUtil.isEmpty(path)) {
					continue;
				}
				if (sb.toString().endsWith("/")) {
					sb.append(path).append("/");
				} else {
					sb.append("/").append(path).append("/");
				}
			}
		}
		if (paths.length == 1) {
			sb.append("/");
		}
		makeDir(sb.toString());//创建文件夹
		return sb.toString();
	}


	/**
	 * 创建文件夹
	 * @param dir
	 */
	public static void makeDir(String dir){
		File fileDir = new File(dir);
		if(!fileDir.exists()) {
			fileDir.mkdirs();
		}
	}

	public static String replace2pdf(String filePath){
		String fileType = Files.getFileExtension(filePath);
		return filePath.replace("."+fileType,".pdf");
	}


	/**
	 * 生成随机数
	 * @return
	 */
	public synchronized static String radom() {
		Date today = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String serialNumber = format.format(today)
				+ new DecimalFormat("0000").format(new Random().nextInt(10000));
		return serialNumber;
	}


	public static String loadStream(InputStream in) throws IOException {
		int ptr = 0;
		in = new BufferedInputStream(in);
		StringBuffer buffer = new StringBuffer();

		while ((ptr = in.read()) != -1) {
			buffer.append((char) ptr);
		}
		return buffer.toString();
	}




	// 4MB buffer
	private static final byte[] BUFFER = new byte[4096 * 1024];

	/**
	 * copy input to output stream - available in several StreamUtils or Streams classes
	 */
	public static void copy(InputStream input, OutputStream output) throws IOException {
		int bytesRead;
		while ((bytesRead = input.read(BUFFER))!= -1) {
			output.write(BUFFER, 0, bytesRead);
		}
	}





	public static void main(String[] args) {
		//String zipFilePath = "D:\\test3.zip";
		//String targetZipFilePath = "D:\\test4.zip";
		//String appendFilePath = "D:\\test.doc";
		//BcxinFileUtil bcxinFileUtil = new BcxinFileUtil();
		//ZipUtil.zip(new File(zipFilePath),targetZipFilePath, FileUtil.getInputStream(appendFilePath));
		//bcxinFileUtil.appendFileToZip(zipFilePath,targetZipFilePath,appendFilePath);

	}
}
