package org.khelekore.jsizer;

import java.awt.EventQueue;
import java.awt.Insets;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

/** A dialog that shows progress during jar file scanning */
class ScanProgressDialog {
    private JDialog d;
    private JLabel status;
    private JLabel currentFile;
    private JProgressBar files;
    private JProgressBar entries;

    public ScanProgressDialog (final JFrame f, final int numFiles) {
	EventQueue.invokeLater (new Runnable () {
		public void run () {
		    buildDialog (f);
		    files.setMaximum (numFiles);
		    d.validate ();
		    d.pack ();
		    d.setLocationRelativeTo (f);
		    d.setVisible (true);
		}
	    });
    }

    private void buildDialog (JFrame parent) {
	d = new JDialog (parent, "Scanning jar files", true);
	GridBagLayout gb = new GridBagLayout ();
	GridBagConstraints c = new GridBagConstraints ();
	d.setLayout (gb);
	
	c.gridx = 0;
	c.gridy = 0;
	c.insets = new Insets (2, 2, 2, 2);
	c.fill = GridBagConstraints.HORIZONTAL;
	c.anchor = GridBagConstraints.NORTH;
	status = new JLabel ("Scanning all jar files...");
	d.add (status, c);
	c.gridy++;
	currentFile = new JLabel (" ");
	d.add (currentFile, c);
	c.gridy++;
	entries = new JProgressBar ();
	d.add (entries, c);
	c.gridy++;
	files = new JProgressBar ();
	d.add (files, c);
    }

    public void nextFile (final String name, final int entries) {
	EventQueue.invokeLater (new Runnable () {
		public void run () {
		    nextFileEDT (name, entries);
		}
	    });
    }

    private void nextFileEDT (String name, int numEntries) {
	currentFile.setText (name);
	files.setValue (files.getValue () + 1);
	entries.setMaximum (numEntries);
	entries.setValue (0);
    }

    public void nextEntry () {
	EventQueue.invokeLater (new Runnable () {
		public void run () {
		    entries.setValue (entries.getValue () + 1);
		}
	    });	
    }
    
    public void dispose () {
	try {
	    EventQueue.invokeAndWait (new Runnable () {
		    public void run () {
			if (d != null)
			    d.dispose ();
		    }
		});
	} catch (InterruptedException e) {
	    e.printStackTrace ();
	} catch (InvocationTargetException e) {
	    e.printStackTrace ();
	}
    }
}
