/*
 * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved.
 */
package ch.psi.plot.utils;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JOptionPane;

/**
 *
 */
public class SwingUtils {

    public static void centerOnParent(Component parent, Component component) {
        Rectangle r = parent.getBounds();
        Dimension w = component.getSize();
        int x = Math.max(r.x + (r.width - w.width) / 2, 4);
        int y = Math.max(r.y + (r.height - w.height) / 2, 4);
        component.setLocation(x, y);
    }

    public static void centerOnScreen(Component component) {
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        component.setLocation(dim.width / 2 - component.getSize().width / 2, dim.height / 2 - component.getSize().height / 2);
    }

    public static Color generateRandomColor() {
        Random random = new Random();

        Color mix = Color.WHITE;
        int red = (random.nextInt(256) + mix.getRed()) / 2;
        int green = (random.nextInt(256) + mix.getGreen()) / 2;
        int blue = (random.nextInt(256) + mix.getBlue()) / 2;

        Color color = new Color(red, green, blue);
        return color;
    }

    public static void showMessage(Component parent, String title, String msg) {
        JOptionPane.showMessageDialog(parent, msg, title, JOptionPane.INFORMATION_MESSAGE, null);
    }

    public static void showException(Component parent, Exception ex) {
        JOptionPane.showMessageDialog(parent, ex.getMessage(), "Exception", JOptionPane.WARNING_MESSAGE, null);
    }

    public static String getString(Component parent, String msg, Object current_value) {
        return JOptionPane.showInputDialog(parent, msg, String.valueOf(current_value));
    }

    public static BufferedImage createImage(Component panel) {
        if (panel == null) {
            return null;
        }
        Dimension size = panel.getSize();
        BufferedImage image = new BufferedImage(
                size.width, size.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        panel.paint(g2);
        return image;
    }    
}
