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

package com.neoworks.jukex.client.html.standard;

import javax.servlet.*;
import java.io.*;
import java.util.*;
import java.net.URL;
import com.neoworks.jukex.*;
import com.neoworks.jukex.tracksource.*;
import com.neoworks.shout.*;
import com.neoworks.util.*;

import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;

/**
 * Startup servlet for JukeX. This servlet is invoked on startup and initialises various services.
 *
 * @author Nigel Atkinson (<a href="mailto:nigel@neoworks.com">nigel@neoworks.com</a>)
 */
public class StartupServlet extends GenericServlet
{
	private static final Category log = Category.getInstance(StartupServlet.class.getName());
	private static final boolean logDebugEnabled = log.isDebugEnabled();
	private static final boolean logInfoEnabled = log.isInfoEnabled();

	//TODO: should read this from a config file
	private static final String PIPELINE_NAME = "servlet";

	/**
	 * Service a request. (This is a noop.)
	 *
	 * @param req The request
	 * @param res The response
	 */
	public void service(ServletRequest req, ServletResponse res)
	{
	}

	/**
	 * Initialise the servlet (called at start up).
	 *
	 * @param config The servlet configuration
	 */
	public void init(ServletConfig config)
	{
		// initialise logging
		String propertiesFilePath = config.getInitParameter("propertiesFilePath");
		
		System.out.println( "Looking for properties file: " + propertiesFilePath );
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		System.out.println( "Got classloader: " + loader.getClass().getName() );
		URL loggingPropertiesURL = loader.getResource( propertiesFilePath );
		if (loggingPropertiesURL == null)
		{
                        Properties loggingProps = new Properties();
                        loggingProps.put("log4j.rootCategory","WARN, A1");
                        loggingProps.put("log4j.appender.A1","org.apache.log4j.FileAppender");
                        loggingProps.put("log4j.appender.A1.File","System.out");
                        loggingProps.put("log4j.appender.A1.layout","org.apache.log4j.PatternLayout");

                        // Print the date in ISO 8601 format
                        loggingProps.put("log4j.appender.A1.layout.ConversionPattern","%d [%t] %-5p %c - %m%n");
			System.out.println("Configuring logging without properties file");
                        PropertyConfigurator.configure(loggingProps);
		} else {
			System.out.println( "Got URL: " + loggingPropertiesURL );
			PropertyConfigurator.configure( loggingPropertiesURL );
		}
						
		String serverName = config.getInitParameter("shoutServer");
		String serverPassword = config.getInitParameter("shoutPassword");
		String serverPort = config.getInitParameter("shoutPort");
		String trackInfoPort = config.getInitParameter("shoutTrackinfoport");
		String name = config.getInitParameter("shoutName");
		String description = config.getInitParameter("shoutDescription");
		String url = config.getInitParameter("shoutUrl");
		String publicShout = config.getInitParameter("shoutPublic");
		ControlPlaybackManager cpm = new ControlPlaybackManager();
		Shouter sh = ShouterFactory.getShouter();
		Stream s = new Stream();
		s.setServerName(serverName);
		s.setPort(Integer.parseInt(serverPort));
		s.setPassword(serverPassword);
		s.setStreamName(name);
		s.setStreamDescription(description);
		s.setURL(url);
		s.setPublicShout(publicShout);
		s.setTrackInfoPort(Integer.parseInt(trackInfoPort));
		sh.setStream(s);
		cpm.registerControlPlayback("office", sh);
		TrackSourcePipeline pipeline = TrackSourcePipeline.getPipeline(PIPELINE_NAME);
		setupPipeline(pipeline);
	}

	private void setupPipeline(TrackSourcePipeline pipeline)
	{
		ListIterator i = pipeline.listIterator();
		
		// See if we can find the Round Robin pipeline element, and if not
		// make a new one and add this playlist into it.
		
		RoundRobinPipelineElement rrpe = null;
		
		while ( i.hasNext() )
		{
			Object thing = i.next();
			if ( thing instanceof RoundRobinPipelineElement )
			{
				rrpe = (RoundRobinPipelineElement) thing;
				log.debug("Found RoundRobinPipelineElement...");
			}
		}
		
		if ( rrpe == null )
		{
			log.debug("Creating RoundRobinPipelineElement...");
			rrpe = new RoundRobinPipelineElement();
			pipeline.addFirst(rrpe );
			pipeline.storePipeline();
			log.debug( "Adding to "+pipeline.getName()+" "+pipeline.getClass().getName());
		}
		
	}
}
