package toy;

import java.awt.*;
import java.awt.event.*;

/**
 * ToySplashWindow is the splash screen that appears when the user first
 * launches the application.
 *
 * @author Brian Tsang
 * @version 7.0
 */

public class ToySplashWindow extends Window
                            implements Runnable
{
    /**
     * The splash component which should fill up the entire splash screen.
     * @serial
     */
    private ToySplash splash;
    /**
     * The thread that will constantly check to see if this window can make an
     * image yet.
     * @see #run()
     * @serial
     */
    private Thread runner;

    /**
     * Construct a ToySplashWindow that will start out correctly sized but
     * blank.  Start the thread that will wait until this Window can start
     * producing images before creating the ToySplash object.
     * @see #run()
     */
    public ToySplashWindow()
    {
        super(new Frame());

        setLayout(null);
        setBounds(
            Toolkit.getDefaultToolkit().getScreenSize().width / 2
                - ToySplash.WIDTH / 2,
            Toolkit.getDefaultToolkit().getScreenSize().height / 2
                - ToySplash.HEIGHT / 2,
            ToySplash.WIDTH,
            ToySplash.HEIGHT
            );

        runner = new Thread(this);
        runner.start();
    }

    /**
     * Stop the thread if it isn't stopped already.
     */
    public void finalize()
    {
        runner = null;
    }

    /**
     * Set the security manager to a more lenient ToySecurityManager, then
     * create and show a ToySplashWindow.
     */
    public static void main(String[] args)
    {
        System.setSecurityManager(new ToySecurityManager());

        ToySplashWindow splashScreen = new ToySplashWindow();

        splashScreen.show();
    }

    /**
     * Implement the Runnable interface to wait for the ability to create
     * images before instantiating ToySplash.  It turns out that a component
     * does not start out with the ability to create images upon instantiation.
     * In any case, ToySplash's constructor requires that its argument have the
     * ability to create images, so we simply wait until we can before creating
     * a ToySplash object.
     */
    public void run()
    {
        Image testImage = null;

        while (testImage == null && runner != null)
        {
            try
            {
                Thread.sleep(100);
            }
            catch (Exception e)
            {
                //whatever
            }

            testImage = this.createImage(100, 100);
        }


        if (testImage != null)
        {
            splash = new ToySplash(this);
            splash.setBounds(
                0,
                0,
                ToySplash.WIDTH,
                ToySplash.HEIGHT
                );
            add(splash);
        }
    }
}
