/**

 * @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.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;
import java.sql.SQLException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTabbedPane;

import com.TwentyCodes.java.OrderProcessor.FileFilter;
import com.TwentyCodes.java.OrderProcessor.ProgressListener;
import com.TwentyCodes.java.OrderProcessor.UncaughtExceptionHandler;
import com.TwentyCodes.java.OrderProcessor.DB.OrderDB;

/**
 * this is the main window and class of this application
 */
public class MainWindow extends JFrame implements ActionListener, ProgressListener{

	private static JButton mLoadFileButton;
	private JFileChooser fc;
	public static OrderDB db;
	private static final long serialVersionUID = 1841715561053331517L;
	private JProgressBar mProgressBar;
	private String mCurrentFile;
	private UncaughtExceptionHandler mExceptionReport = new UncaughtExceptionHandler(this.getClass());
	private static JLabel orderCountLabel;
	private static JLabel mWarningLabel;

	/**
	 * Creates a new MainWindow
	 * @author ricky barrette
	 */
	public MainWindow() {
		
		Thread.setDefaultUncaughtExceptionHandler(mExceptionReport);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        fc = new JFileChooser();
        fc.setFileFilter(new FileFilter());
        
        JTabbedPane tabbedPane = new JTabbedPane();

        tabbedPane.addTab("Main", initializeMainPanel());
        tabbedPane.addTab("Search Orders", new SearchPanel(this));
//        tabbedPane.addTab("Show All Orders", new ShowAllPanel(this));
        tabbedPane.addTab("Settings", new SettingsPanel());
        

        this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
        
        this.setVisible(true);
        this.pack();
	}
	
	/**
	 * initializes the main layout
	 * 
	 * @author ricky barrette
	 */
	private JPanel initializeMainPanel() {
		setTitle("Twenty Codes, LLC Order Database");
		setIconImage(new ImageIcon(getClass().getResource("/database.png")).getImage());
		
		JPanel mainPanel = new JPanel(new BorderLayout());
		JPanel panel = new JPanel();
		mainPanel.add(panel);
		
		
		//load button
		mLoadFileButton = new JButton("Load File", new ImageIcon(getClass().getResource("/database_add.png")));
		mLoadFileButton.addActionListener(this);
		
		
		mWarningLabel = new JLabel("");
		orderCountLabel = new JLabel("");
		
		panel.add(new JLabel("Total Orders in the database:"));
		panel.add(orderCountLabel);
		
		loadDatabase();
		
		panel.add(mLoadFileButton);
		
		panel.add(mWarningLabel);
		
		//progress bar
		mProgressBar = new JProgressBar();
		mProgressBar.setStringPainted(true);
		mainPanel.add(mProgressBar, BorderLayout.SOUTH);
				
		return mainPanel;
	}

	public static void loadDatabase() {
		//order count labels
		try {
			db = new OrderDB();
			orderCountLabel.setText(db.getCount()+"");
			mWarningLabel.setText("");
		} catch (SQLException e) {
			e.printStackTrace();
			mWarningLabel.setText(e.getMessage());
			mWarningLabel.setVisible(true);
		} catch (SocketException e) {
			mWarningLabel.setText(e.getMessage());
			mWarningLabel.setVisible(true);
		} catch (NullPointerException e){
			mWarningLabel.setText("Database not avilable");
			mWarningLabel.setVisible(true);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	/**
	 * called when a button is clicked
	 * (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	@Override
	public void actionPerformed(ActionEvent e) {

		/**
		 * Prepares the progress bar, and loads the file using an executer to prevent UI hangups
		 */
		if(e.getSource() == mLoadFileButton){
			if(fc.showOpenDialog(MainWindow.this) == JFileChooser.APPROVE_OPTION){
				mLoadFileButton.setEnabled(false);
				db.setOnProgressListerner(this);
				mProgressBar.setIndeterminate(true);
				mCurrentFile = fc.getSelectedFile().toString();
				mProgressBar.setString(mCurrentFile);
				
				java.util.concurrent.Executors.newSingleThreadExecutor().submit(new Runnable() { 
					public void run() { 
						try {
							db.load(fc.getSelectedFile());
							
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						} catch (SQLException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						} catch (ClassNotFoundException e) {
							e.printStackTrace();
						}
					}
				});

				pack();
			} else {
				mProgressBar.setIndeterminate(false);
			}
		}
	}
	
	/**
	 * called then the progress of the order db is updated
	 * (non-Javadoc)
	 * @see com.TwentyCodes.java.OrderProcessor.ProgressListener#onProgressUpdate(int)
	 * @author ricky barrette
	 */
	@Override
	public void onProgressUpdate(String string, boolean isIndeterminate, int progress, int max) {
		mProgressBar.setMaximum(max);
		mProgressBar.setValue(progress);
		mProgressBar.setString(string);
		if(mProgressBar.isIndeterminate()) {
			mProgressBar.setIndeterminate(isIndeterminate);
			pack();
		}
		if(progress >= mProgressBar.getMaximum()){
			mLoadFileButton.setEnabled(true);
			try {
				orderCountLabel.setText(db.getCount()+"");
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (SocketException e) {
				mWarningLabel.setText(e.getMessage());
			}
		}
	}			

}