/*
 * This file is part of the Vamsas Client version 0.2. 
 * Copyright 2010 by Jim Procter, Iain Milne, Pierre Marguerite, 
 *  Andrew Waterhouse and Dominik Lindner.
 * 
 * Earlier versions have also been incorporated into Jalview version 2.4 
 * since 2008, and TOPALi version 2 since 2007.
 * 
 * The Vamsas Client is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *  
 * The Vamsas Client is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with the Vamsas Client.  If not, see <http://www.gnu.org/licenses/>.
 */
package uk.ac.vamsas.client.simpleclient;

public abstract class WatcherElement {

  private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory
      .getLog(VamsasFileWatcherElement.class);

  protected FileWatcher watcher = null;

  protected WatcherCallBack handler = null;

  /**
   * set this to false to stop the thread
   */
  protected boolean watchForChange = true;

  /**
   * true when the handler is being called for this watcher
   */
  protected boolean handlerCalled = false;

  public WatcherElement(WatcherCallBack handler) {
    this.handler = handler;
  }

  /**
   * will instruct watcher to stop and wait around for one WATCH_SLEEP before
   * returning. If no thread is running then it returns immediately.
   */
  public void haltWatch() {
    // set the flag to skip this watch element.
    watchForChange = false;
    if (log.isDebugEnabled())
      log.debug("haltWatch on " + watcher.getSubject());
    endWatch();
    if (log.isDebugEnabled())
      log.debug("haltWatch completed on " + watcher.getSubject());
  }

  /**
   * called by haltWatch before clearing the FileWatcher reference.
   * 
   */
  protected abstract void endWatch();

  /**
   * called to generate the watcher object by enableWatch and in doWatch
   * 
   */
  protected abstract void initWatch();

  /**
   * implemented for debug information purposes.
   * 
   * @return Informative string about what the watcher is watching
   */
  protected abstract String getSubject();

  /**
   * must be called by implementations of enablewatch
   */
  protected void enableWatch() {
    if (log.isDebugEnabled())
      log.debug("enableWatch on " + getSubject());
    watchForChange = true;
    initWatch();
    if (log.isDebugEnabled())
      log.debug("enableWatch returning on " + getSubject());
  }

  /**
   * Originally from the uk.ac.vamsas.test.simpleclient.ArchiveClient method
   * 
   * @return true if the handler was called for a changeEvent
   */
  public boolean doWatch() {
    if (!watchForChange || handler == null)
      return false;
    if (watcher == null)
      initWatch(); // somehow not done the first time
    handlerCalled = false;
    Lock doclock = null;
    try {
      doclock = watcher.getChangedState();
    } catch (Exception e) {
      log.error("Whilst watching " + watcher.getSubject(), e);
    }
    if (doclock == null)
      return false;
    /*
     * handlerCalled=true; if (log.isDebugEnabled())
     * log.debug("Triggering watchEvent for change on "+watcher.getSubject());
     * boolean finish=!handler.handleWatchEvent(this, doclock); doclock=null; //
     * TODO: check that lock should really be released rather than dereferenced
     * if (finish) haltWatch(); else enableWatch(); handlerCalled=false;
     */
    this.callHandler(doclock);
    return true;
  }

  /**
   * Calls the current eventhandler
   * 
   * @param doclock
   *          the lock on the watch file
   */
  protected void callHandler(Lock doclock) {
    if (log.isDebugEnabled())
      log.debug("Triggering watchEvent for change on " + watcher.getSubject());
    boolean finish = !handler.handleWatchEvent(this, doclock);
    doclock = null; // TODO: check that lock should really be released rather
                    // than dereferenced
    if (finish)
      haltWatch();
    else
      enableWatch();
    handlerCalled = false;
  }

  /**
   * @return the handler
   */
  public WatcherCallBack getHandler() {
    return handler;
  }

  /**
   * @return the handlerCalled
   */
  public boolean isHandlerCalled() {
    return handlerCalled;
  }

  /**
   * 
   * @return true if watcher is enabled
   */
  public boolean isWatchEnabled() {
    return watchForChange;
  }

  /**
   * @param handler
   *          the handler to set
   */
  public void setHandler(WatcherCallBack handler) {
    this.handler = handler;
  }

  /**
   * @return the watcher
   */
  public FileWatcher getWatcher() {
    return watcher;
  }
}
