package org.pietschy.command;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: andrew
 * Date: Jun 4, 2005
 * Time: 12:36:52 PM
 * To change this template use File | Settings | File Templates.
 */
class
FaceHelper
implements PropertyChangeListener
{
   private Command command;

   private HashMap faces = new HashMap();
   private Face defaultFace;


   public FaceHelper(Command command)
   {
      this.command = command;
   }

   public void installFace(Face face)
   {
      if (face == null)
         throw new NullPointerException("face is null");

      Face existing = (Face) faces.get(face.getName());

      if (existing != null)
         face.removePropertyChangeListener(this);

      face.addPropertyChangeListener(this);

      faces.put(face.getName(), face);

      if (defaultFace == null || face.isNameEqualTo(Face.DEFAULT))
         defaultFace = face;

   }

   public Face
   getFace(String faceName, boolean createFace, String[] alternativeFaces)
   {
      Face face = (Face) faces.get(faceName);

      if (face != null)
         return face;

      if (createFace)
      {
         face = createFace(faceName);
         return face;
      }

      for (int i = 0; i < alternativeFaces.length; i++)
      {
         face = (Face) faces.get(alternativeFaces[i]);
         if (face != null)
            return face;
      }

      return defaultFace;
   }



   public Face
   getDefaultFace(boolean createIfMissing)
   {
      if (defaultFace == null && createIfMissing)
         defaultFace = createFace(Face.DEFAULT);

      return defaultFace;
   }


   /**
    * Creates a new empty face with the specified name.
    * <p>
    * The face is automatically added to the command so there is no need
    * explicitly installFace it.
    *
    * @param faceName the name of the face, "button" for example.
    * @return the newly created face.
    */
   private Face createFace(String faceName)
   {
      FaceManager faceManager = command.getCommandManager().getFaceManager();
      Face face = faceManager.createFace(command, faceName);
      installFace(face);
      return face;
   }

   public void
   propertyChange(PropertyChangeEvent event)
   {
      command.configureButtonAppearances((Face) event.getSource());
   }


   public boolean faceExists(String faceName)
   {
      return faces.get(faceName) != null;
   }
}
