import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.media.*;
import javax.swing.*;


/**
 * A JPanel that contains a media player 
 * (using the Java Media Framework)
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison University
 *
 */
public class PlayerPanel extends    JPanel
			 implements ControllerListener
{
    protected boolean    includeVisual, includeControls;
    protected Player     player;


    /**
     * Constructor
     *
     */
    public PlayerPanel(boolean includeVisual, 
                       boolean includeControls)
    {
	player = null;

	this.includeVisual   = includeVisual;
	this.includeControls = includeControls;

	setLayout(new BorderLayout());
    }
    


    /**
     * Load a media file
     *
     * @param fn  The name of the file
     */
    public void loadFile(String fn)
    {
	Component       c;
	URL             url;

	try {

	    url = new URL("file:"+
                          System.getProperty("user.dir")+
                          "/"+
                          fn);

	    player = Manager.createPlayer(url);
	    player.addControllerListener(this);
	    player.start();

	} catch (MalformedURLException mue) {

	    JOptionPane.showMessageDialog(this, 
			  "Unable to open file!");

	} catch (NoPlayerException npe) {
	    
	    JOptionPane.showMessageDialog(this,
			  "Unable to create a player!");

	} catch (IOException ioe) {
	    
	    JOptionPane.showMessageDialog(this,
			  "Unable to connect to source!");
	}

    }



    /**
     * Handle controllerUpdate events 
     * (required by ControllerListener)
     *
     * @param evt   The ControllerEvent
     */
    public synchronized void controllerUpdate(ControllerEvent evt) 
    {
	Component c;

	if (evt instanceof RealizeCompleteEvent) {

	    c = player.getVisualComponent();
	    if ((c != null) && (includeVisual)) {

		add(c, BorderLayout.CENTER);
	    }

	    c = player.getControlPanelComponent();
	    if ((c != null) && (includeControls)) {

		add(c, BorderLayout.SOUTH);
	    }

	    // Force a re-layout
	    validate();
	}

    }
}


