//----------------------------------------------------------------------------
// COMPONENT NAME: LPEX Editor
//
// © Copyright IBM Corporation 2005, 2008
// All Rights Reserved.
//
// DESCRIPTION:
// ClockCommand - sample user-defined command (clock)
//----------------------------------------------------------------------------

package com.ibm.lpex.samples;

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

/**
 * Sample command <b>clock</b> - time the execution of an editor command.
 * Note that the (wall clock) time displayed is approximate at best, and it
 * might well reflect more of the Java class loading, memory management, garbage
 * collection, and JIT progress than any actual LPEX command execution time.
 * This command cannot replace a real tracing utility.
 *
 * <p>Here is the ClockCommand
 * <a href="doc-files/ClockCommand.java.html">source code</a>.</p>
 *
 * <p>To run this sample:
 * <ul>
 *  <li>Define this user command via an editor preference page, where available,
 *    or from the editor command line:
 *    <pre>set commandClass.clock com.ibm.lpex.samples.ClockCommand</pre></li>
 *  <li>Run it from the editor command line, for example:
 *    <pre>clock parse all</pre></li>
 * </ul></p>
 *
 * @see com.ibm.lpex.samples All the samples
 */
public class ClockCommand implements LpexCommand
{
 /**
  * Runs this command.
  * Displays the approximate time used to run an editor command.
  * It times the execution of the command specified in the parameters
  * followed by the <b>screenShow view</b> command.
  *
  * @param lpexView the document view in which the command was issued
  * @param parameters the editor command to run
  */
 public boolean doCommand(LpexView lpexView, String parameters)
 {
  if (lpexView != null)
   {
    if ("?".equals(parameters.trim())) // command help
     {
      lpexView.doCommand("set messageText Syntax: clock [<editor command>]");
      return true;
     }

    // clear message line
    lpexView.doCommand("set messageText");

    // time the command (-as- use JDK 1.5's System.nanoTime()?!)
    long start = System.currentTimeMillis(); // ms since 1/1/1970 00:00:00 UTC
    lpexView.doCommand(parameters);
    lpexView.doCommand("screenShow view");   // include view's screen refresh
    long end = System.currentTimeMillis();

    // keep any new message
    String msg = lpexView.query("messageText");
    if (msg == null)
     {
      msg = "";
     }
    // remove any extra timing of clocking ourselves :-)
    else if (msg.startsWith("["))
     {
      int i = msg.indexOf("ms] ");
      if (i > 0)
       {
        msg = msg.substring(i + "ms] ".length());
       }
     }

    // display result
    lpexView.doCommand("set messageText [" + (end-start) + "ms] " + msg);
   }

  return true;
 }
}