/**
 * @author Twenty Codes, LLC
 * @author ricky barrette
 * @date Dec 18, 2010
 */

package com.TwentyCodes.java.OrderProcessor.UI;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

import com.TwentyCodes.java.OrderProcessor.ProgressListener;

/**
 * This panel will be used to display all Vehicles in the VechicleDB
 */
public class ShowAllPanel extends JPanel implements ActionListener, ProgressListener {

	private static final long serialVersionUID = -8416144493079733535L;
	private JProgressBar mProgressBar;
	private OrderPane mOutput;
	private JFrame mFrame;
	
	/**
	 * Creates a new ShowAllDialog
	 */
	public ShowAllPanel(final JFrame frame){
		super(new BorderLayout());
		mFrame = frame;
		
//		setTitle("Show All Orders");
//		setIconImage(new ImageIcon(getClass().getResource("/database.png")).getImage());
		
		JButton ok = new JButton("Refresh", new ImageIcon(getClass().getResource("/process.png")));
		ok.addActionListener(this);
		mOutput = new OrderPane();
		mProgressBar = new JProgressBar();
		add(mProgressBar, BorderLayout.SOUTH);
		add(mOutput, BorderLayout.CENTER);
		add(ok, BorderLayout.NORTH);
		mProgressBar.setString("Loading from Database");
		mProgressBar.setStringPainted(true);
		try {
			MainWindow.db.setOnProgressListerner(this);
		} catch (NullPointerException e) {
			e.printStackTrace();
			mOutput.setText("Database not initialized");
		}
		frame.pack();
		
		
		
		setVisible(true);
	}	

	@Override
	public void actionPerformed(ActionEvent arg0) {
		java.util.concurrent.Executors.newSingleThreadExecutor().submit(new Runnable() { 
			public void run() { 
				try {
					mOutput.displayOrders(MainWindow.db.getAllOrders());
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mFrame.pack();
			}
		});
	}

	@Override
	public void onProgressUpdate(String string, boolean isIndeterminate, int progress, int max) {
		mProgressBar.setMaximum(max);
		mProgressBar.setValue(progress);
		mProgressBar.setIndeterminate(isIndeterminate);
		mProgressBar.setString(string);
		if(progress >= mProgressBar.getMaximum()){
			mFrame.pack();
			mProgressBar.setString("Done");
		}
	}
}
