package interfacing;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.*;

/**
 * This frame is just a Frame that opens when the Application launches and it in
 * turn load the MainFrame class
 * 
 * @author Majd Kokaly
 * 
 */
public class OpeningFrame extends JFrame {
	private static final long serialVersionUID = -6237472440906594782L;
	ImageIcon picture = new ImageIcon("Introduction3.jpg");
	JLabel jLPicture = new JLabel();
	JProgressBar progressBar = new JProgressBar(0, 100);

	public OpeningFrame() {

		this.getContentPane().add(jLPicture, BorderLayout.CENTER);
		this.getContentPane().add(progressBar, BorderLayout.SOUTH);
		this.jLPicture.setIcon(picture);
		
		this.progressBar.setSize(1024, 20);
		this.setSize(1024, 788);
		this.setResizable(false);
		this.setUndecorated(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Centering The Frame
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = this.getSize();
		if (frameSize.height > screenSize.height)
			frameSize.height = screenSize.height;
		if (frameSize.width > screenSize.width)
			frameSize.width = screenSize.width;
		this.setLocation((screenSize.width - frameSize.width) / 2,
				(screenSize.height - frameSize.height) / 2);

	}


	public static void main(String[] args) {
		OpeningFrame openingFrame = new OpeningFrame();
		openingFrame.setVisible(true);

		MainFrame mainFrame = null;

		OpeningThread OT = new OpeningThread(openingFrame.progressBar,
				openingFrame, mainFrame);
		OT.start();

		OT.setMainFrame(MainFrame.creatMainFrame());

	}

	static class OpeningThread extends Thread {
		public JProgressBar bar;
		public JFrame openingFrame;
		private JFrame mainFrame;

		public OpeningThread(JProgressBar bar, JFrame openingFrame,
				JFrame mainFrame) {
			this.bar = bar;
			this.openingFrame = openingFrame;
			this.mainFrame = mainFrame;
		}

		public synchronized JFrame getMainFrame() {
			return mainFrame;
		}

		public synchronized void setMainFrame(JFrame mainFrame) {
			this.mainFrame = mainFrame;
		}

		public void run() {
			for (int i = 0; i <= 100; i += 5) {
				this.bar.setValue(i);
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {

					e.printStackTrace();
				}
			}

			while (this.getMainFrame() == null) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			this.openingFrame.dispose();
			this.mainFrame.setVisible(true);
		}
	}

}
