package client;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Iterator;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import client.ChatFrame.MassMessageSender;
import network.Host;
import msg.Message;
import msg.MessageSender;
import util.ClipboardManager;
import util.Constants;
import util.Globals;
@SuppressWarnings("serial")
public class ImageFrame extends JPanel
implements MouseListener {
/** Frame y panels para visualizar las imagenes */
private JFrame frame;
private JPanel drawingPane;
/** Contiene los botones, combo de hosts, etc */
private JPanel commandsPane;
/** Componentes para las acciones */
JComboBox hostComboBox;
JButton send;
JButton closeButton;
/** Imagen a mostrar */
private Image img;
/** Indica si viene desde el clipboard o si viene de un mensaje recibido*/
private boolean fromClipboard = true;
private ImageIcon imgIcon;
public ImageFrame(boolean fromClipboard) {
super(new BorderLayout());
this.fromClipboard = fromClipboard;
//Set up the drawing area.
drawingPane = new DrawingPane();
drawingPane.setBackground(Color.white);
drawingPane.addMouseListener(this);
//Boton de envio
commandsPane = new JPanel();
send = new JButton("Enviar");
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ( ((Host)hostComboBox.getSelectedItem()).getHostName().equalsIgnoreCase(Constants.MASS_MESSAGE_TEXT))
new Thread(new MassMessageSender()).start();
else
enviarImagen(((Host)hostComboBox.getSelectedItem()).getHostName(), ((Host)hostComboBox.getSelectedItem()).getHostIP(), false);
}
});
//Hosts de destino
hostComboBox = new JComboBox();
hostComboBox.setPreferredSize(new Dimension(300,20));
reloadComboOptions();
commandsPane.add(hostComboBox);
commandsPane.add(send);
//Put the drawing area in a scroll pane.
JScrollPane scroller = new JScrollPane(drawingPane);
scroller.setPreferredSize(new Dimension(800,600));
//Lay out this demo.
add(scroller, BorderLayout.CENTER);
if (this.fromClipboard)
add(commandsPane, BorderLayout.SOUTH);
}
/** The component inside the scroll pane. */
public class DrawingPane extends JPanel {
protected void paintComponent(Graphics g) {
if (fromClipboard)
{
if(img != null)
g.drawImage(img,0,0, this);
}
else
{
if(imgIcon != null)
imgIcon.paintIcon(this, g, 0, 0);
}
}
}
//Handle mouse events.
public void mouseClicked(MouseEvent e){
// nada que hacer por aca
if (img == null && imgIcon == null)
return;
// actualizar scrolls y dimensiones
pintate();
}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
public static void showImage(String hostName) {
//Create and set up the window.
JFrame frame = new JFrame("Enviar imagen");
//Create and set up the content pane.
ImageFrame panel = new ImageFrame(true);
panel.frame = frame;
panel.setOpaque(true); //content panes must be opaque
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
panel.reloadComboOptions();
// Seleccionar el hostName indicado por parametro
Host host = Host.findHost(hostName);
if (host != null)
panel.getHostComboBox().setSelectedItem(host);
panel.setImg(ClipboardManager.getClipboard());
if (panel.getImg()==null)
{
frame.dispose();
return;
}
//Display the window.
frame.pack();
frame.setVisible(true);
panel.pintate();
panel.send.requestFocus();
}
public void pintate()
{
// redimensionar segun el tipo de dato cargado
if (fromClipboard)
drawingPane.setPreferredSize(new Dimension(img.getWidth(this) ,img.getHeight(this)));
else
drawingPane.setPreferredSize(new Dimension(imgIcon.getIconWidth(), imgIcon.getIconHeight()));
drawingPane.revalidate();
drawingPane.repaint();
}
/**
* Envia la imagen al destinatario
*/
private void enviarImagen(String hostName, String hostIP, boolean massive)
{
if (img == null)
return;
// si no estoy online, no puedo enviar!
if (!Globals.online)
{
JOptionPane.showMessageDialog(null, "ESTAS OFFLINE!!", Constants.APPLICATION_NAME_MSG, JOptionPane.INFORMATION_MESSAGE);
return;
}
// esta online el destinatario?
Host host = Host.findHost(hostName);
if (host == null || !host.isConnected())
return;
System.out.println("Enviar una imagen..." );
Message message = new Message();
message.setMessageKind(Constants.MESSAGE_KIND_IMAGE);
message.setMessageContent(new ImageIcon(img));
message.setReceiver(hostName);
message.setReceiverIP(hostIP);
message.setSender(Globals.localHostName);
message.setSenderIP(Globals.localIP);
message.setToAll(massive);
new Thread(new MessageSender(message)).start();
if (!massive)
frame.dispose();
}
public static void showReceivedImage(ImageIcon image, String sender) {
//Create and set up the window.
JFrame frame = new JFrame("HEY! " + sender + " te mando una imagen!");
//Create and set up the content pane.
ImageFrame panel = new ImageFrame(false);
panel.frame = frame;
panel.setOpaque(true); //content panes must be opaque
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
panel.fromClipboard = false;
panel.imgIcon = image;
//Display the window.
frame.pack();
frame.setVisible(true);
panel.pintate();
}
/**
* Recarga las opciones a mostrar en el combo de hosts
*/
private synchronized void reloadComboOptions()
{
hostComboBox.removeAllItems();
hostComboBox.addItem(new Host(Constants.MASS_MESSAGE_TEXT, Constants.MASS_MESSAGE_TEXT, true));
Iterator<Host> it = Globals.hosts.iterator();
while (it.hasNext())
hostComboBox.addItem(it.next());
}
/**
* Thread aparte para el envio de imagenes masivas
*/
public class MassMessageSender implements Runnable
{
@Override
public void run()
{
for (int i=0; i < Globals.hosts.size() ; i++)
if (!Globals.hosts.elementAt(i).getHostName().equalsIgnoreCase(Globals.localHostName) && Globals.hosts.elementAt(i).isConnected())
{
enviarImagen(Globals.hosts.elementAt(i).getHostName(), Globals.hosts.elementAt(i).getHostIP(), true);
try {Thread.sleep(Constants.threadSafeDelayMS);} catch (Exception e) { System.out.println("Error en run de ChatFrame: " + e.getMessage()); }
}
frame.dispose();
}
}
/** --- GETTERS y SETTERS */
public Image getImg()
{
return img;
}
public void setImg(Image img)
{
this.img = img;
}
public JComboBox getHostComboBox()
{
return hostComboBox;
}
}