/*
 * *************************************************
 * Copyright (c) 2018 QMTH. All Rights Reserved.
 * Created by Deason on 2018-06-19 14:24:38.
 * *************************************************
 */

package cn.com.qmth.examcloud.core.questions.base;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class ImageUtils {
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
    private static final String TAG_IMG = "img";
    private static final String UNIT = "px";
    private static final int MAX_WIDTH = 350;
    private static final String STYLE_WIDTH = "width:%spx;";
    private static final String STYLE_HEIGHT = "height:%spx;";
    public static final String ATTR_WIDTH = "width";
    public static final String ATTR_HEIGHT = "height";

    /**
     * 如果图片尺寸过大，则按比例缩放图片的宽度高度
     */
    public static String reSizeImg(String html) {
        if (html == null) {
            return "";
        }
        Document document = Jsoup.parse(html);
        Elements elements = document.getElementsByTag(TAG_IMG);
        for (Element element : elements) {
            int width = ImageUtils.parseValue(element.attr("style"), "width");
            int height = ImageUtils.parseValue(element.attr("style"), "height");
            //log.debug(width + " - " + height);
            element.removeAttr("width");
            element.removeAttr("height");
            String widthStr = "";
            String heightStr = "";
            boolean isOutWidth = false;
            if (width > 0) {
                if (width > MAX_WIDTH) {
                    isOutWidth = true;
                    widthStr = String.format(STYLE_WIDTH, MAX_WIDTH);
                } else {
                    widthStr = String.format(STYLE_WIDTH, width);
                }
            }
            if (height > 0) {
                if (isOutWidth) {
                    heightStr = String.format(STYLE_HEIGHT, calculateHeight(width, height, MAX_WIDTH));
                } else {
                    heightStr = String.format(STYLE_HEIGHT, height);
                }
            }
            element.attr("style", widthStr + heightStr);
        }
        String bodyHtml = document.body().html();
        //log.debug(bodyHtml);
        return bodyHtml;
    }

    public static int calculateHeight(int oldWidth, int oldHeight, int newWidth) {
        if (oldWidth == 0) {
            return 0;
        }
        int newHeight = (newWidth * oldHeight) / oldWidth;
        return newHeight;
    }

    public static int parseValue(String styleValue, String attrName) {
        if (styleValue == null || "".equals(styleValue)) {
            return 0;
        }
        try {
            styleValue = styleValue.replaceAll(" ", "");
            String[] attrs = styleValue.toLowerCase().split(";");
            for (String attr : attrs) {
                if (!attr.startsWith(attrName)) {
                    continue;
                }
                String[] values = attr.split(":");
                if (values.length > 1) {
                    String value = values[1].toLowerCase().replaceAll(UNIT, "");
                    return Integer.parseInt(value);
                }
            }
        } catch (Exception e) {
            //do nothing
        }
        return 0;
    }

    public static Map<String, Integer> parseImageWidthAndHeight(String imgTagContent) {
        Map<String, Integer> result = new HashMap<>();
        if (imgTagContent == null) {
            return result;
        }

        Document document = Jsoup.parse(imgTagContent);
        Elements elements = document.getElementsByTag(TAG_IMG);
        if (elements == null || elements.isEmpty()) {
            return result;
        }

        //只处理第一个图片元素
        Element element = elements.first();
        String widthContent = element.attr(ATTR_WIDTH);
        String heightContent = element.attr(ATTR_HEIGHT);
        result.put(ATTR_WIDTH, parseValue(widthContent));
        result.put(ATTR_HEIGHT, parseValue(heightContent));
        return result;
    }

    public static int parseValue(String attrValue) {
        if (attrValue == null || "".equals(attrValue)) {
            return 0;
        }
        try {
            attrValue = attrValue.replaceAll(" ", "");
            String value = attrValue.toLowerCase().replaceAll(UNIT, "");
            return Integer.parseInt(value);
        } catch (Exception e) {
            return 0;
        }
    }

    public static void mainTest(String[] args) {
        String html = "<p><IMG src=\"abc\" width=\"800px\" height=\"400px\" style=\"width: 600PX; height:300PX;\"/><img src=\"xyz\" style=\"width:300px;\"/></p>";
        log.debug(ImageUtils.reSizeImg(html));

        Map<String, Integer> data = parseImageWidthAndHeight(html);
        log.debug(data.get(ATTR_WIDTH) + " - " + data.get(ATTR_HEIGHT));
    }

}