/**
 * GUI Commands
 * Copyright 2004 Andrew Pietsch
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id: VisibleCommandGroup.java,v 1.10 2005/09/18 00:37:19 pietschy Exp $
 */

package org.pietschy.command.demo;

import org.pietschy.command.*;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class
VisibleCommandGroup
extends CommandGroup
{
   static final String _ID_ = "$Id: VisibleCommandGroup.java,v 1.10 2005/09/18 00:37:19 pietschy Exp $";

   private Timer timer;

   public VisibleCommandGroup(CommandManager container)
   {
      super(container, "menu.visible");
      // since this group gets so many members added we use a timer to coalese all the adds into
      // a single rebuild request.
      timer = new Timer(500, new ActionListener()
      {
         public void actionPerformed(ActionEvent e)
         {
            rebuildAllPopups();
            timer.stop();
         }
      });

      export();
   }

   /**
    * Overrides the default behaviour to build a group of commands the control the visibility
    * of all other registered commands.
    */
   public void commandRegistered(CommandManagerEvent event)
   {
      Command command = event.getCommand();
      // don't include ourselves or any of the main menu items!!
      if (equals(command) || command.getId().startsWith("menu."))
         return;

      // don't rebuild now, and restart the timer.
//      installFace(new VisibleCommand(command));
      add(new VisibleCommand(command), false);
      timer.restart();
   }

   public class
   VisibleCommand
   extends ToggleCommand
   {
      static final String _ID_ = "$Id: VisibleCommandGroup.java,v 1.10 2005/09/18 00:37:19 pietschy Exp $";
      private Command command;

      private VisibleCommand(Command c)
      {
         super();
         this.command = c;
         // installFace new face that tracks the one we're controlling..
         Face face = VisibleCommand.this.getDefaultFace(true);
         face.setText(c.getDefaultFace().getText() + " (" + c.getId() + ")");
         setSelected(c.isVisible());
      }

      protected void handleSelection(boolean selected)
      {
         command.setVisible(selected);
      }
   }
}
