package sale.stdforms;

import sale.SaleProcess;
import sale.ProcessErrorCodes;

import java.io.Serializable;

/**
  * <i>Abstract</i> super class of all strategies that are used with FormSheets.
  *
  * <p>Strategies are usually used to parameterize certain responses to user actions in standard FormSheets.
  * Good examples are the parameterized responses to the buttons in a {@link data.stdforms.TwoTableFormSheet}.
  * </p>
  *
  * <p>This <i>abstract</i> base class knows only about error handling. It uses
  * {@link ErrorHandler error handling strategies} so that subclasses can easily be adapted to behave
  * differently in case of an error.</p>
  *
  * @author Steffen Zschaler
  * @version 2.0 18/08/1999
  * @since v2.0
  */
public abstract class FormSheetStrategy extends Object implements ProcessErrorCodes, Serializable {

  /**
    * Interface that defines a error handling strategy for a {@link FormSheetStrategy}.
    *
    * @author Steffen Zschaler
    * @version 2.0 18/08/1999
    * @since v2.0
    */
  public static interface ErrorHandler extends Serializable, ProcessErrorCodes {
    /**
      * Handle an error.
      *
      * @param p the process in which the error occurred.
      * @param nErrorCode an int value describing the error.
      *
      * @override Always
      */
    public void error (SaleProcess p, int nErrorCode);
  }

  /**
    * The default error handler. This will pass the error on to the process'
    * {@link sale.SaleProcess#error(int)} method.
    */
  public static final ErrorHandler DEFAULT_ERROR_HANDLER = new ErrorHandler() {
    public void error (SaleProcess p, int nErrorCode) {
      p.error (nErrorCode);
    }
  };

  /**
    * An alternative error handler that will pop up a modeless {@link MsgForm} in the process.
    */
  public static final ErrorHandler MSG_POPUP_ERROR_HANDLER = new ErrorHandler() {
    public void error (SaleProcess p, int nErrorCode) {
      MsgForm mfs = new MsgForm ("Error", p.getErrorMsg (nErrorCode), false);

      try {
        p.getContext().popUpFormSheet (p, mfs);
      }
      catch (InterruptedException ie) {}
    }
  };

  /**
    * The current error handler. Defaults to the {@link #DEFAULT_ERROR_HANDLER}.
    *
    * @serial
    */
  protected ErrorHandler m_ehErrHandler = DEFAULT_ERROR_HANDLER;

  /**
    * Set the current error handler.
    *
    * @param ehErrHandler the new error handler.
    *
    * @override Never
    */
  public void setErrorHandler (ErrorHandler ehErrHandler) {
    if (ehErrHandler != null) {
      m_ehErrHandler = ehErrHandler;
    }
    else {
      m_ehErrHandler = DEFAULT_ERROR_HANDLER;
    }
  }

  /**
    * Handle an error.
    *
    * <p>This is delegated to the error handler.</p>
    *
    * @param p the process in which the error occurred.
    * @param nErrorCode an int describing the error.
    *
    * @override Never
    */
  public void error (SaleProcess p, int nErrorCode) {
    m_ehErrHandler.error (p, nErrorCode);
  }
}