/*
 * 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;

import java.util.Iterator;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Watches a bunch of VamsasFile states, calling the associated event handler
 * when anything changes.
 * 
 * @author JimP
 * 
 */
public class VamsasFileWatcherThread extends Thread {
  private Log log = LogFactory.getLog(VamsasFileWatcherThread.class);

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Thread#run()
   */
  EventGeneratorThread client = null;

  private Vector elements = null;

  public VamsasFileWatcherThread(EventGeneratorThread client) {
    this.client = client;
    elements = new Vector();
  }

  public void addElement(WatcherElement welement) {
    elements.addElement(welement);
  }

  public void removeElemenet(WatcherElement welement) {
    elements.removeElement(welement);
  }

  public void clearElements() {
    elements.clear();
  }

  /**
   * true if the thread is running
   */
  boolean running = false;

  /**
   * true if the watcher loop is in progress
   */
  boolean watching = false;

  public void haltWatchers() {
    if (!watching)
      return;
    watching = false;
    // wait arount for WATCH_SLEEP milliseconds before returning
    // in the hope that the watcher loop has stopped
    try {
      interrupt();
      long time = System.currentTimeMillis() + WATCH_SLEEP;
      while (running && time > System.currentTimeMillis()) {
        Thread.sleep(1);
      }
    } catch (Exception e) {
    }
    ;
    if (running)
      log.warn("haltWatchers returning whilst thread is still running.");
  }

  /**
   * time between checks for changes of state on the file
   */
  public int WATCH_SLEEP = 30;

  /**
   * check each watcher in sequence, monitoring any events generated. Then wait
   * WATCH_SLEEP milliseconds before checking all again (if there were no
   * events)
   */
  public void run() {
    running = true;
    watching = true;
    log.debug("Starting WatcherThread poll loop");
    while (watching) {
      boolean wait = true;
      Iterator watchers = elements.iterator();
      while (watching && watchers.hasNext()) {
        WatcherElement watch = (WatcherElement) watchers.next();
        if (watch.doWatch()) {
          wait = false;
          log.debug("Event generated for watcher on "
              + watch.getWatcher().getSubject());
        }
      }
      if (watching && wait) {
        try {
          Thread.sleep(WATCH_SLEEP);
        } catch (InterruptedException e) {
        }
        ;
      }
    }
    log.debug("Finishing WatcherThread poll loop");
    running = false;
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Thread#interrupt()
   */
  public void interrupt() {
    // TODO: make thread gracefully interrupt watchers so that any handlers
    // finish doing what they were doing
    // super.interrupt();
  }

}
