/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2003-2006 RSSOwl Development Team                                  **
 **   http://www.rssowl.org/                                                 **
 **                                                                          **
 **   All rights reserved                                                    **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the Eclipse Public License 1.0 which accompanies this     **
 **   distribution, and is available at:                                     **
 **   http://www.rssowl.org/legal/epl-v10.html                               **
 **                                                                          **
 **   A copy is found in the file epl-v10.html and important notices to the  **
 **   license from the team is found in the textfile LICENSE.txt distributed **
 **   in this package.                                                       **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Contributors:                                                          **
 **     RSSOwl - initial API and implementation (bpasero@rssowl.org)         **
 **                                                                          **
 **  **********************************************************************  */

package net.sourceforge.rssowl.controller.thread;

import net.sourceforge.rssowl.controller.GUI;
import net.sourceforge.rssowl.controller.NewsTabFolder;
import net.sourceforge.rssowl.util.GlobalSettings;
import net.sourceforge.rssowl.util.search.SearchDefinition;

import java.util.Vector;

/**
 * The RSS queue loader is a thread that loads feed from a Vector. The feeds are
 * loaded feed by feed beginning with the first element of the vector.
 * 
 * @author <a href="mailto:bpasero@rssowl.org">Benjamin Pasero </a>
 * @version 1.2.3
 */
public class FeedQueueLoader extends Thread {
  private Vector feedQueue;
  int counter;
  private boolean isRunning;

  /** Miliseconds to wait before loading the next chunk of Feeds */
  private static final int GAP_BETWEEN_LOADING = 3000;

  /**
   * Instantiate a new FeedQueueLoader Thread
   */
  public FeedQueueLoader() {
    feedQueue = new Vector();
    setDaemon(true);
    setName("Queue Loader Thread");
  }

  /**
   * Add a feed to the queue
   * 
   * @param url URL of the feed
   */
  public void addFeed(String url) {

    /** Keep the order */
    if (feedQueue.contains(url))
      feedQueue.remove(url);

    feedQueue.add(url);
  }

  /**
   * @see java.lang.Thread#run()
   */
  public void run() {

    /** Thread now running */
    isRunning = true;

    /** For each feed in the feed queue until is interrupted or app was closed */
    counter = 0;
    LoadingLoop: while (!feedQueue.isEmpty() && GUI.isAlive() && !isInterrupted()) {

      /**
       * This is a hack. In the rare case that the user wants to open more Feeds
       * on startup, than the number of maximum parallel connections (32 by
       * default), sleep a bit before proceeding. This will minimize the number
       * of Threads and Connections being created at the same time.
       */
      if (counter > GlobalSettings.maxConnectionCount) {
        counter = 0;
        try {
          sleep(GAP_BETWEEN_LOADING);
        } catch (InterruptedException e) {
          break LoadingLoop;
        }
      }

      /** Load feed in display runnable */
      if (GUI.isAlive() && !isInterrupted()) {
        GUI.display.syncExec(new Runnable() {
          public void run() {

            /** If no Tabs are used, only load last Feed of List */
            String feedUrl = GlobalSettings.displaySingleTab ? getLastFeed() : getNextFeed();

            /** Load the Feed */
            GUI.rssOwlGui.loadNewsFeed(feedUrl, SearchDefinition.NO_SEARCH, true, true, NewsTabFolder.DISPLAY_MODE_FOCUS_FIRST);
            counter++;
          }
        });
      }

      /** If no Tabs are used, only load one Feed */
      if (GlobalSettings.displaySingleTab)
        break LoadingLoop;
    }

    /** Thread no longer running */
    isRunning = false;
  }

  /**
   * Start the RSS Queue loader Thread
   */
  public void startThread() {
    start();
  }

  /**
   * Stop the RSS Queue loader Thread
   */
  public void stopThread() {
    isRunning = false;
    interrupt();
  }

  /**
   * Get the last feed to load
   * 
   * @return String URL of the last feed
   */
  String getLastFeed() {
    return (String) feedQueue.remove(feedQueue.size() - 1);
  }

  /**
   * Get the next feed to load
   * 
   * @return String URL of the next feed
   */
  String getNextFeed() {
    return (String) feedQueue.remove(0);
  }

  /**
   * Check wether this Thread is currently running.
   * 
   * @return boolean TRUE if this Thread is currently running, FALSE otherwise.
   */
  public boolean isRunning() {
    return isRunning;
  }
}