package cn.com.qmth.stmms.api.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import cn.com.qmth.stmms.biz.utils.PictureTag;

public class ImageBuildUtil {

    public static final String DEFAULT_FONT_NAME = "Arial";

    public static final int DEFAULT_FONT_SIZE = 60;

    public static final int DEFAULT_LINE_GAP = 10;

    /**
     * 根据指定的标记内容绘制新的图片
     * 
     * @param image
     * @param tags
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static BufferedImage buildTagImage(BufferedImage image, List<PictureTag> tags) throws FileNotFoundException,
            IOException {
        if (tags != null && !tags.isEmpty()) {
            BufferedImage newImg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = newImg.createGraphics();
            g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            g.setColor(Color.RED);
            for (PictureTag tag : tags) {
                if (tag.getContent() == null) {
                    continue;
                }
                int fontSize = tag.getSize() > 0 ? tag.getSize() : DEFAULT_FONT_SIZE;
                if (tag.getLeft() <= 1 || tag.getTop() <= 1) {
                    tag.setLeft(tag.getLeft() * image.getWidth());
                    tag.setTop(tag.getTop() * image.getHeight());
                }
                int left = (int) Math.max(fontSize, tag.getLeft());
                int top = (int) Math.max(fontSize, tag.getTop());
                g.setFont(new Font(DEFAULT_FONT_NAME, Font.PLAIN, fontSize));
                for (String content : tag.getContent()) {
                    g.drawString(content, left, top);
                    top = top + fontSize + DEFAULT_LINE_GAP;
                }
            }
            g.dispose();
            image = newImg;
        }
        return image;
    }
}
