/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.social.twitter.api.impl;

import java.io.IOException;
import java.util.List;
import java.util.Queue;

import org.springframework.social.twitter.api.StreamDeleteEvent;
import org.springframework.social.twitter.api.StreamListener;
import org.springframework.social.twitter.api.StreamWarningEvent;
import org.springframework.social.twitter.api.Tweet;

import com.fasterxml.jackson.databind.ObjectMapper;

class StreamDispatcher implements Runnable {

	private final List<StreamListener> listeners;

	private ObjectMapper objectMapper;
	
	private volatile boolean active;

	private final Queue<String> queue;

	public StreamDispatcher(Queue<String> queue, List<StreamListener> listeners) {
		this.queue = queue;
		this.listeners = listeners;
		objectMapper = new ObjectMapper();
		objectMapper.addMixInAnnotations(Tweet.class, TweetMixin.class);
		objectMapper.addMixInAnnotations(StreamDeleteEvent.class, StreamDeleteEventMixin.class);
		objectMapper.addMixInAnnotations(StreamWarningEvent.class, StreamWarningEventMixin.class);
		active = true;
	}

	public void run() {
		while(active) {
			String line = queue.poll();
			if(line == null || line.length() == 0) return;
			
			// TODO: handle scrub_geo, status_withheld, user_withheld, disconnect, friends, events, 
			
			try {
				if (line.contains("in_reply_to_status_id_str")) { // TODO: This is kinda hacky
					handleTweet(line);
				} else if (line.startsWith("{\"limit")) {
					handleLimit(line);
				} else if (line.startsWith("{\"delete")) {
					handleDelete(line);
				} else if (line.startsWith("{\"warning")) {
					handleWarning(line);
				}
			} catch (IOException e) {
				// TODO: Should only happen if Jackson doesn't know how to map the line
			}
		}
	}
	
	public void stop() {
		active = false;
	}
	
	private void handleDelete(String line) throws IOException {
		final StreamDeleteEvent deleteEvent = objectMapper.readValue(line, StreamDeleteEvent.class);
		for (final StreamListener listener : listeners) {
			new Thread(new Runnable() {
				public void run() {
					listener.onDelete(deleteEvent);
				}
			}).start();
		}
	}

	private void handleLimit(String line) throws IOException {
		final TrackLimitEvent limitEvent = objectMapper.readValue(line, TrackLimitEvent.class);
		for (final StreamListener listener : listeners) {
			new Thread(new Runnable() {
				public void run() {
					listener.onLimit(limitEvent.getNumberOfLimitedTweets());
				}
			}).start();
		}
	}

	private void handleTweet(String line) throws IOException {
		final Tweet tweet = objectMapper.readValue(line, Tweet.class);
		for (final StreamListener listener : listeners) {
			new Thread(new Runnable() {
				public void run() {
					listener.onTweet(tweet);
				}
			}).start();
		}
	}
	
	private void handleWarning(String line) throws IOException {
		final StreamWarningEvent warningEvent = objectMapper.readValue(line, StreamWarningEvent.class);
		for (final StreamListener listener : listeners) {
			new Thread(new Runnable() {
				public void run() {
					listener.onWarning(warningEvent);
				}
			}).start();
		}
	}
	
}

@@ -737,16 +737,136 @@
 l.Queue;
+%0Aimport java.util.concurrent.ExecutorService;%0Aimport java.util.concurrent.Executors;%0Aimport java.util.concurrent.Future;
 %0A%0Aimport
@@ -1361,16 +1361,55 @@
 %3E queue;
+%0A%09%0A%09private final ExecutorService pool;
 %0A%0A%09publi
@@ -1534,16 +1534,58 @@
 teners;%0A
+%09%09pool = Executors.newCachedThreadPool();%0A
 %09%09object
@@ -2602,16 +2602,35 @@
  false;%0A
+%09%09pool.shutdown();%0A
 %09%7D%0A%09%0A%09pr
@@ -2833,34 +2833,55 @@
 eners) %7B%0A%09%09%09
-new Thread
+Future%3C?%3E result = pool.submit(
 (new Runnabl
@@ -2950,39 +2950,32 @@
 nt);%0A%09%09%09%09%7D%0A%09%09%09%7D)
-.start(
 );%0A%09%09%7D%0A%09%7D%0A%0A%09priv
@@ -3170,34 +3170,55 @@
 eners) %7B%0A%09%09%09
-new Thread
+Future%3C?%3E result = pool.submit(
 (new Runnabl
@@ -3312,39 +3312,32 @@
 ());%0A%09%09%09%09%7D%0A%09%09%09%7D)
-.start(
 );%0A%09%09%7D%0A%09%7D%0A%0A%09priv
@@ -3507,34 +3507,55 @@
 eners) %7B%0A%09%09%09
-new Thread
+Future%3C?%3E result = pool.submit(
 (new Runnabl
@@ -3617,39 +3617,32 @@
 et);%0A%09%09%09%09%7D%0A%09%09%09%7D)
-.start(
 );%0A%09%09%7D%0A%09%7D%0A%09%0A%09pri
@@ -3856,18 +3856,39 @@
 %0A%09%09%09
-new Thread
+Future%3C?%3E result = pool.submit(
 (new
@@ -3974,20 +3974,13 @@
 %09%09%7D%0A
+
 %09%09%09%7D)
-.start(
 );%0A%09

Add CachedThreadPool to optimize thread management