/***************************************************************************
    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.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.sql.SQLException;
import org.apache.log4j.Category;

/**
 * PipelineElement that plays the results of a query once.
 *
 * @author Nigel Atkinson <a href="mailto:nigel@neoworks.com">nigel@neoworks.com</a>
 */
public class OnetimeSearchPipelineElement extends TrackSourcePipelineElementSkeleton
{
	private static final Category log = Category.getInstance(SearchPipelineElement.class.getName());
	private static final boolean logDebugEnabled = log.isDebugEnabled();
	private static final boolean logInfoEnabled = log.isInfoEnabled();
	private Query query;
	private List trackIds;

	/**
	 * Public constructor
	 */
	public OnetimeSearchPipelineElement()
	{
		super("OnetimeSearch");
		trackIds = new ArrayList();
	}

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

	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 to use for selecting tracks
	 *
	 * @param q The Query
	 */
	public synchronized void setQuery(Query q)
	{
		query = q;
		trackIds = new ArrayList();
		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());
		} 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 (i.hasNext() && j < count)
			{
				retVal.add(ts.getTrack(((Long)i.next()).longValue()));
				j++;
			}
			if (retVal.size() < count)
			{
				retVal.addAll(delegatePeekTracks(count - retVal.size()));
			}
		} else {
			retVal = delegatePeekTracks(count);
		}
		return retVal;
	}

	/**
	 * Get a string representation of the query
	 *
	 * @return Tne JukeXQL query String
	 */
	public String getQueryString()
	{
		return query.getOriginalQuery();
	}

	/**
	 * Clone this RandomiserPipelineElement
	 *
	 * @return A clone of this RandomiserPipelineElement
	 */
	public Object clone()
	{
		return new OnetimeSearchPipelineElement();
	}
	
	/**
	 * Return a String describing what, in general terms, this TrackSource does
	 *
	 * @return A String
	 */
	public String getDescription()
	{
		return "OnetimeSearchPipelineElement: This element takes the results of a search, and plays it once";
	}
	
	/**
	 * Return a String summarising the configuration of the task the source is
	 * performing
	 *
	 * @return A String
	 */
	public String getSummary()
	{
		if ( super.isEnabled() )
		{
			if ( this.trackIds.size() > 0 )
			{
				return "There are "+this.trackIds.size()+" left to play from the search "+this.query.getOriginalQuery();
			}
			else
			{
				return "There are currently no tracks left for this element to play";
			}
		}
		else
		{
			return "Disabled";
		}
	}
	
}
