package com.mooctest.image;

import com.mooctest.util.ImageUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImageDownload {

    public static void createImage(String imgurl, String taskId, String filePath) throws Exception {

        String path = ImageUtil.IMAGE_PATH + taskId + "/" + filePath;

        File imageFile = new File(path);
        if (checkExist(imageFile)) {
            System.out.println("数据已存在");
            return;
        }

        URL url = new URL(encode(imgurl, "utf-8"));
        BufferedImage image = null;
        int retryTimes = 3;
        for (int i = 0; i < retryTimes; i++) {
            try {
                image = ImageIO.read(url);
                break;
            } catch (IOException e) {
                System.out.println("image download fail " + filePath + " download times: " + (i + 1));
                if (i+1 == retryTimes)
                    throw e;
            }
        }
//        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        InputStream inputStream = conn.getInputStream(); // 通过输入流获得图片数据
//        byte[] getData = readInputStream(inputStream); // 获得图片的二进制数据

        FingerPrint fp = new FingerPrint(image);


        FileOutputStream fos = new FileOutputStream(imageFile);
        fos.write(fp.getBinaryzationMatrix());
        fos.close();
    }

    public 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();

    }

    public static boolean checkExist(File file) throws Exception {
        File file2 = new File(file.getParent());
        if (!file2.isDirectory()) {// 判断文件目录是否存在
            file2.mkdirs();
        }
        if (!file.exists()) {//判断文件是否存在
            file.createNewFile();// 创建文件
        } else {
            return true;
        }
        return false;
    }

    private static String zhPattern = "[\\u4e00-\\u9fa5]+";

    public static String encode(String str, String charset)
            throws UnsupportedEncodingException {
        str = str.replaceAll(" ", "+");// 对空字符串进行处理
        Pattern p = Pattern.compile(zhPattern);
        Matcher m = p.matcher(str);
        StringBuffer b = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
        }
        m.appendTail(b);
        return b.toString();
    }

}
