package sample.textdetection.frame;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * ImageとRectangleを表示するJFrame
 * @author sakamoto
 */
public class ImageFrame extends JFrame {
    /**
     * UID
     */
    private static final long serialVersionUID = 1L;

    private Image image;
    private Font font = new Font("Console", Font.PLAIN, 34);

    private List<ImageFrameNode> nodes = new ArrayList<>();
    /**
     * 画像が大きすぎる場合があるので縮小率を設定
     */
    private double scale = 0.4;

    public ImageFrame(String title) {
        setTitle(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBackground(Color.white);
        setLocationRelativeTo(null);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.scale(scale, scale);
        if (image != null) {
            g.drawImage(image, 0, 0, null);
        }
        nodes.forEach((n) -> {
            g.setColor(n.color);
            g.setFont(font);
            FontMetrics fm = g.getFontMetrics();
            int th = fm.getHeight();

            g.drawRect(n.rectangle.x, n.rectangle.y, n.rectangle.width, n.rectangle.height);
            // g2.scale(2.0, 2.0);
            // g.drawString(n.text, (int)(n.rectangle.x * scale * 0.5), (int)((n.rectangle.y
            // - 5) * scale* 0.5));

            int tx = n.rectangle.x + n.rectangle.width + th / 2;
            int[] ty = { n.rectangle.y + 30 };
            n.textList.forEach(t -> {
                g.drawString(t, tx, ty[0]);
                ty[0] += th;
            });
            // g.drawString(n.text, (int)(n.rectangle.x ), (int)((n.rectangle.y - 5)));
        });
    }

    public void addNodes(List<ImageFrameNode> nodes) {
        this.nodes.addAll(nodes);
    }

    public void setImage(URL imageURL) {
        try {
            setImage(ImageIO.read(imageURL));
        } catch (IOException e) {
            image = null;
            JOptionPane.showMessageDialog(this, "Image load error. " + e.getMessage());
        }
    }

    public void setImage(Image img) {
        if (img == null) {
            return;
        }
        image = img;
        int hegiht = image.getHeight(null);
        int width = image.getWidth(null);
        setSize((int) (width * scale), (int) (hegiht * scale));
        repaint();
    }

}
