package speiger.src.ui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.event.ComponentAdapter;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.util.Map;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import speiger.src.data.Registry;
import speiger.src.data.TaggedImage;

public class LocationDisplay extends JDialog {
	private static final long serialVersionUID = 3803744617604239360L;
	
	public LocationDisplay(JFrame owner, String name, Map<String, TaggedImage> images) {
		setTitle(name+" Images");
		setBounds(0, 0, 700, 700);
		setResizable(true);
		setLocationRelativeTo(owner);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		getContentPane().setLayout(new BorderLayout());
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		getContentPane().add(tabbedPane, BorderLayout.CENTER);

		images.forEach((K, V) -> {
			JPanel panel = new JPanel(new BorderLayout());
			tabbedPane.addTab(firstLetterUppercase(K), panel);
			Thread.ofPlatform().name("Image Loader", 1).start(() -> {
				BufferedImage image = Registry.INSTANCE.getImage(V);
				if(image == null) {
					EventQueue.invokeLater(() -> tabbedPane.remove(panel));
					return;
				}
				EventQueue.invokeLater(() -> {
					panel.add(new ImagePanel(image, this), BorderLayout.CENTER);
					repaint();
				});
			});
		});	
		setVisible(true);
		addComponentListener(new ComponentAdapter() {
			public void componentResized(java.awt.event.ComponentEvent e) {
				repaint();
			};
		});
	}
	
	public static String firstLetterUppercase(String string) {
		if(string == null || string.isEmpty()) {
			return string;
		}
		String first = Character.toString(string.charAt(0));
		return string.replaceFirst(first, first.toUpperCase());
	}
	
	private static class ImagePanel extends Panel {
		private static final long serialVersionUID = 5945747347624323542L;
		BufferedImage image;

		public ImagePanel(BufferedImage image, JDialog owner) {
			this.image = image;

			addMouseListener(new MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					owner.dispose();
				};
			});
		}
		
		@Override
		public void paint(Graphics g) {
			super.paint(g);
			g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
		}
	}
}
