package com.developpez.adiguba.demo;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

import org.jdesktop.swingworker.SwingWorker;

public class DemoSwingWorker extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	private static final int SECONDS = 10;

	private final JLabel label = new JLabel(" ");

	/**
	 * Constructeur par défaut.
	 */
	public DemoSwingWorker() {
		super("Demo SwingWorker :: " + System.getProperty("java.vm.name") + " "
				+ System.getProperty("java.vm.version"));
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setJMenuBar(createMenuBar());
		getContentPane().add(createPanel());
		pack();
		setLocationRelativeTo(null);
	}

	/**
	 * Méthode d'attente : on attend 10 secondes
	 */
	private void attente() {
		try {
			Thread.sleep(SECONDS * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Action associé au menu : on affiche le texte sous l'îcone
	 */
	public void actionPerformed(ActionEvent e) {
		this.label.setText(e.getActionCommand());
	}

	/**
	 * Creation de la barre de menu et des différentes options.
	 */
	private JMenuBar createMenuBar() {
		JMenuBar menuBar = new JMenuBar();

		for (int i = 1; i < 5; i++) {
			JMenu menu = new JMenu("Menu " + i);
			menuBar.add(menu);
			for (int j = 1; j < 10; j++) {
				JMenu subMenu = new JMenu("Sous-Menu " + i + "-" + j);
				menu.add(subMenu);
				for (int k = 1; k < 10; k++) {
					JMenuItem item = new JMenuItem("Item " + i + "-" + j + "-"
							+ k);
					item.addActionListener(this);
					subMenu.add(item);
				}
			}
		}
		return menuBar;
	}

	/**
	 * Création du panel centrale de l'application (JLabel avec une icône animé +
	 * 2 boutons)
	 */
	private JComponent createPanel() {

		/* Initialisation du label */
		this.label.setIcon(new ImageIcon(getClass().getResource(
				"duke.running.gif")));
		this.label.setHorizontalTextPosition(SwingConstants.CENTER);
		this.label.setVerticalTextPosition(SwingConstants.BOTTOM);

		/* Creation du bouton 1 */
		final JButton button1 = new JButton(SECONDS + "s (avec update())");
		button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				button1.setEnabled(false); // je désactive le bouton
				update(getGraphics()); // raffraichissement de l'interface
				attente(); // j'attends 5000 miliSec. (5sec)
				button1.setEnabled(true); // je réactives le bouton
			}
		});

		/* Creation du bouton 2 */
		final JButton button2 = new JButton(SECONDS + "s (avec SwingWorker)");
		button2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				button2.setEnabled(false); // je désactive le bouton
				new SwingWorker() {
					@Override
					protected Object doInBackground() throws Exception {
						// Traitement effectué en tâche de fond
						attente();
						return null;
					}

					@Override
					protected void done() {
						// Mise à jours de l'interface à la fin du traitement
						button2.setEnabled(true);
					}
				}.execute(); // Exécution de la tâche
			}
		});

		/* Création du panel */
		JPanel panel = new JPanel();
		panel.add(label);
		panel.add(button1);
		panel.add(button2);
		JScrollPane scroll = new JScrollPane(panel);
		scroll.setBorder(null);
		return scroll;

	}

	public static void main(java.lang.String[] args) {
		
		// Gestion par défaut des exceptions :
		try {
			Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
				public void uncaughtException(Thread t, Throwable e) {
					JOptionPane.showMessageDialog(null,
							"<html><h3 style='color:red'>Erreur d'exécution du programme :</h3>" +
							e.getClass().getSimpleName() + " : " + e.getMessage() + "<br><br>",
						
							"Erreur " + e.getClass().getSimpleName() , JOptionPane.ERROR_MESSAGE);
				}
			});
		} catch (SecurityException e) {
			// ignored (interdit dans les appli JWS non-signé)
		}

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {

				try {
					// LookAndFell système :
					UIManager.setLookAndFeel(UIManager
							.getSystemLookAndFeelClassName());
				} catch (Exception e) {
					e.printStackTrace();
				}

				// Redimensionnement dynamique des fenêtres
				Toolkit.getDefaultToolkit().setDynamicLayout(true);

				new DemoSwingWorker().setVisible(true);
			}
		});

	}

}
