/***************************************************************************
    Copyright          : (C) 2002 by Neoworks Limited. All rights reserved
    URL                : http://www.neoworks.com
 ***************************************************************************/
/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

/*
 * TrackSourcePipelineElementSkeleton.java
 *
 * Created on 02 May 2002, 14:48
 */

package com.neoworks.jukex.tracksource;

import com.neoworks.jukex.*;
import com.neoworks.jukex.query.*;

import java.util.Map;
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.sql.SQLException;
import org.apache.log4j.Category;

/**
 * PipelineElement that repeatedly plays the results of a Query. This will tend to become
 * intensely annoying especially if the query is something like: <code>SELECT Title WHERE
 * Title = "%blobby%"</code>
 *
 * @author Nigel Atkinson <a href="mailto:nigel@neoworks.com">nigel@neoworks.com</a>
 */
public class AnnoyingPipelineElement extends TrackSourcePipelineElementSkeleton implements SearchPipelineElement
{
	private static final Category log = Category.getInstance(AnnoyingPipelineElement.class.getName());
	private static final boolean logDebugEnabled = log.isDebugEnabled();
	private static final boolean logInfoEnabled = log.isInfoEnabled();

	private Query query;
	private LinkedList trackIds;

	/**
	 * Public constructor
	 */
	public AnnoyingPipelineElement()
	{
		super("Annoying");
		trackIds = new LinkedList();
	}

	/**
	 * Public constructor
	 *
	 * @param q The query to execute
	 */
	public AnnoyingPipelineElement(Query q)
	{
		super("Annoying");
		query = q;
		trackIds = new LinkedList();
		executeQuery();
	}

	/**
	 * Execute the query
	 */
	private void executeQuery()
	{
		if (query != null)
		{
			try {
				AttributeValueResultSet avrs = query.getAttributeValues();
				while (avrs.next())
				{
					trackIds.add(new Long(avrs.getTrackId()));
				}
			} catch (SQLException e) {
				log.warn("Exception encountered while executing query", e);
			}
		}
	}

	/**
	 * Set the query
	 *
	 * @param q The new query
	 */
	public synchronized void setQuery(Query q)
	{
		query = q;
		trackIds = new LinkedList();
		executeQuery();
	}

	/**
	 * Get the current state of this PipelineElement for persisting
	 *
	 * @return a String keyed Map of objects representing the state of 
	 * this PipelineElement, e.g. for a Playlist this would be information
	 * allowing the reconstruction of the current playlist queue.
	 */
	public Map getState()
	{
		Map retVal = new HashMap();
		retVal.put("name",name);
		retVal.put("query",query);
		retVal.put("enabled",new Boolean(isEnabled()));
		return retVal;
	}

	/**
	 * Load the configuration of this PipelineElement
	 *
	 * @param state a Map of values keyed by Strings representing the state of this PipelineElement.
	 * @return success
	 */
	public boolean setState( Map state )
	{
		query = (Query)state.get("query");
		name = (String)state.get("name");
		if (((Boolean)state.get("enabled")).booleanValue())
		{
			enable();
		} else {
			disable();
		}
		executeQuery();
		return true;
	}

	/**
	 * Get the next Track
	 *
	 * @return a Track object
	 */
	public synchronized Track getNextTrack()
	{
		Track retVal = null;
		if (isEnabled() && trackIds.size() > 0)
		{
			retVal = TrackStoreFactory.getTrackStore().getTrack(((Long)trackIds.remove(0)).longValue());
			trackIds.addLast(new Long(retVal.getId()));
		} else {
			retVal = delegateGetNextTrack();
		}
		return retVal;
	}

	/**
	 * Peek up the track list
	 *
	 * @param count The number of tracks to peek
	 * @return A List of Track objects
	 */
	public synchronized List peekTracks(int count)
	{
		List retVal = null;
		if (isEnabled() && trackIds.size() > 0)
		{
			retVal = new ArrayList();
			TrackStore ts = TrackStoreFactory.getTrackStore();
			Iterator i = trackIds.iterator();
			int j = 0;
			while (j < count)
			{
				i = trackIds.iterator();
				while (i.hasNext() && j < count)
				{
					retVal.add(ts.getTrack(((Long)i.next()).longValue()));
					j++;
				}
			}
		} else {
			retVal = delegatePeekTracks(count);
		}
		return retVal;
	}

	public String getQueryString()
	{
		return (query == null)?"":query.getOriginalQuery();
	}

	/**
	 * Clone this AnnoyingPipelineElement
	 *
	 * @return A clone of this RandomiserPipelineElement
	 */
	public Object clone()
	{
		return new AnnoyingPipelineElement();
	}
	
	/**
	 * Return a String describing what, in general terms, this TrackSource does
	 *
	 * @return A String
	 */
	public String getDescription()
	{
		return "AnnoyingPipelineElement: This element plays the results of query in order, repeatedly";
	}	
	
	/**
	 * Return a String summarising the configuration of the task the source is
	 * performing
	 *
	 * @return A String
	 */
	public String getSummary()
	{
		if ( super.isEnabled() )
		{
			return "Currently repeating the tracks returned by the query "+( (this.query != null)?this.query.getOriginalQuery():"[no query]" );
		}
		else
		{
			return "Currently disabled";
		}
	}
}
