/*
 * *************************************************
 * Created by Deason on 2018-07-23 17:32:42.
 * *************************************************
 */
package cn.com.qmth.examcloud.core.questions.service.temp;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImgDataUtils {
    private static final Logger log = LoggerFactory.getLogger(ImgDataUtils.class);

    /**
     * 获取html中所有图片的src地址
     */
    public static List<String> parseImageSrc(String content) {
        if (content == null) {
            return new ArrayList<>();
        }
        List<String> images = new ArrayList<>();
        String reg = "(<img.*src\\s*=\\s*(.*?)[^>]*?>)";
        Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            String img = matcher.group();
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                images.add(m.group(1));
            }
        }
        return images;
    }

    /**
     * 获取html中所有图片标签
     */
    public static List<String> parseImages(String content) {
        if (content == null) {
            return new ArrayList<>();
        }
        List<String> images = new ArrayList<>();
        String reg = "<(img|IMG)(.*?)(/>|></img>|>)";
        Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            String img = matcher.group();
            images.add(img);
        }
        return images;
    }

    /**
     * 获取网络图片的流数据，并base64编码
     */
    public static String loadImageToBase64(String imgUrl) {
        byte[] data = loadImage(imgUrl);
        if (data == null) {
            return null;
        }
        return convertDataToBase64(data);
    }

    /**
     * 获取网络图片的流数据，并保存到文件
     */
    public static void loadImageToFile(String imgUrl, String filePath) {
        byte[] data = loadImage(imgUrl);
        if (data == null) {
            return;
        }
        convertDataToFile(data, filePath);
    }

    /**
     * 获取网络图片的流数据(不支持https)
     */
    public static byte[] loadImage(String imgUrl) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(imgUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(15 * 1000);//超时响应时间为15秒
            conn.setReadTimeout(15 * 1000);//超时响应时间为15秒
            InputStream inStream = conn.getInputStream();
            return readInputStream(inStream);//得到图片的二进制数据
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    public static String convertDataToBase64(byte[] data) {
        try {
            return Base64.encodeBase64String(data);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    public static byte[] convertBase64ToData(String data) {
        try {
            return Base64.decodeBase64(data);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    public static void convertDataToFile(byte[] data, String filePath) {
        if (data == null) {
            return;
        }
        FileOutputStream outStream = null;
        try {
            File imageFile = new File(filePath);
            outStream = new FileOutputStream(imageFile);
            outStream.write(data);
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    public static byte[] readInputStream(InputStream inStream) {
        if (inStream == null) {
            return null;
        }
        try {
            int len;
            byte[] bytes = new byte[1024];
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            while ((len = inStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            return outStream.toByteArray();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

}