package com.jay.monitor.data.server.utils;

import com.github.hui.quick.plugin.md.Html2ImageWrapper;
import com.github.hui.quick.plugin.md.MarkDown2HtmlWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Module TODO
 * @Description TODO
 * @Author liukaixiong
 * @Date 2020/12/14 18:07
 */
public class MarkDownUtils {

    private static Logger logger = LoggerFactory.getLogger(MarkDownUtils.class);

    private static String defaultFormat = "jpg";

    public static InputStream mdToImage(String mdText) {
        return mdToImage(mdText, defaultFormat);
    }

    public static InputStream mdToImage(String mdText, String formatName) {
        try {
            String html = mdToHtml(mdText);
            BufferedImage img = Html2ImageWrapper.ofDoc(html)
                    //                .setW(1000)
                    .setAutoW(true)
                    .setAutoH(true)
                    .setOutType(defaultFormat)
                    .build()
                    .asImage();
            return bufferedImageToInputStream(img, defaultFormat);
        } catch (Exception e) {
            logger.error("md转img失败", e);
        }
        return null;
    }

    public static String mdToHtml(String mdText) {
        return MarkDown2HtmlWrapper.parse(mdText);
    }

    private static InputStream bufferedImageToInputStream(BufferedImage image, String formatName) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, formatName, os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (IOException e) {
            logger.error("流转换异常", e);
        }
        return null;
    }
}
