//----------------------------------------------------------------------------
// COMPONENT NAME: LPEX Editor
//
// © Copyright IBM Corporation 1998, 2006
// All Rights Reserved.
//
// DESCRIPTION:
// TestCommand - sample user-defined command
//----------------------------------------------------------------------------

package com.ibm.lpex.samples;

import com.ibm.lpex.core.LpexCommand;
import com.ibm.lpex.core.LpexStringTokenizer;
import com.ibm.lpex.core.LpexView;

/**
 * Sample command - display a message.
 * Running this command displays, on the editor message line, a short message
 * identifying itself and its parameters.
 *
 * <p>Here is the TestCommand <a href="doc-files/TestCommand.java.html">source
 * code</a>.</p>
 *
 * <p>To run this sample:
 * <ul>
 *  <li>Define the command via an editor preference page, where available, or
 *   from the editor command line:
 *    <pre>set commandClass.testCommand com.ibm.lpex.samples.TestCommand</pre></li>
 *  <li>Run it from the editor command line:
 *    <pre>testCommand [<i>parameters</i>]</pre></li>
 * </ul></p>
 *
 * <p>A user command is a Java class that implements the
 * com.ibm.lpex.core.LpexCommand interface.</p>
 *
 * @see com.ibm.lpex.samples All the samples
 */
public class TestCommand implements LpexCommand
{
 /**
  * Runs this command.
  *
  * @param lpexView the document view in which the command was issued
  * @param parameters optional command parameters
  */
 public boolean doCommand(LpexView lpexView, String parameters)
 {
  if (lpexView != null)
   {
    String command = commandName(this, lpexView);
    parameters = parameters.trim();
    if ("?".equals(parameters)) // command help
     {
      lpexView.doCommand("set messageText Syntax: " + command + " [<parameters>]");
      return true;
     }

    if (parameters.length() != 0)
     {
      command += ' ' + parameters;
     }

    lpexView.doCommand("set messageText Command \"" + command + "\" was run.");
   }

  return true;
 }

 /**
  * Returns the name assigned to an instance of a user-defined command
  * in the specified view.
  *
  * @param lpexCommand instance of an LPEX command
  * @param lpexView a document view in which it is defined
  * @return command name as defined with e.g., <b>set commandClass.</b>
  */
 public static String commandName(LpexCommand lpexCommand, LpexView lpexView)
 {
  String className = (lpexCommand != null)? lpexCommand.getClass().getName() : null;
  if (className != null && lpexView != null)
   {
    LpexStringTokenizer st = new LpexStringTokenizer(lpexView.query("commands"));
    while (st.hasMoreTokens())
     {
      String commandName = st.nextToken();
      // first name found is OK (there may, though unlikely, be more)
      if (className.equals(lpexView.query("commandClass." + commandName)))
       {
        return commandName;
       }
     }
   }
  return className;
 }
}