/*
 * Created on Nov 13, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.prolixtech.jaminid;

import java.util.HashMap;

/**
 * @author Constantinos Michael
 * 
 */
public class StreamingOracle extends ContentOracle {
    // IdentityHashMap streams = new IdentityHashMap();

    HashMap<String, StreamBundle> streamspaths = new HashMap<String, StreamBundle>();

    public static final String PATH_START = "/streams/";

    static StreamingOracle theInstanceSO = new StreamingOracle();

    public StreamingOracle() {
        // do nothing
    }

    public String publishStream(StreamBundle a, String path) {
        String fullpath = PATH_START + path;
        a.setFullPath(fullpath);

        streamspaths.put(fullpath, a);

        return fullpath;
    }

    public static ContentOracle Instance() {

        return theInstanceSO;
    }

    public String demultiplex(Request cReqL, Response cRepL) {
        StreamBundle streams = streamspaths.get(cReqL
                .getLocation());

        if (streams != null) {

            MusicStream stream = streams.getStream(cReqL);
            cRepL.setHeaderLine(ProtocolResponseHeader.Content_Type, "audio/mpeg");
            cRepL.setHeaderLine(ProtocolResponseHeader.Icy_MetaData, "-1");
            return null;

        }

        return "Streaming Error: Not Found";
    }

    public int getStreamInterval() {

        return 3000;
    }

    public byte[] getNextBatch(Request cReqL, Response cRepL) {
        StreamBundle streams = streamspaths.get(cReqL
                .getLocation());
        if (streams != null) {
            MusicStream stream = streams.getStream(cReqL);
            if (stream != null) {
                System.out.println("Sending next batch to " + cReqL + " at "
                        + stream.getPos());
                int bytesToRead = stream.getByteSizeForTime(this
                        .getStreamInterval());
                System.out.println("will return " + bytesToRead);
                return stream.readNext(bytesToRead);
            }

            return null;
        }

        return null;

    }

}