package org.wanna.jabbot.binding.cli;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wanna.jabbot.binding.AbstractRoom;
import org.wanna.jabbot.binding.BindingListener;
import org.wanna.jabbot.binding.BindingMessage;
import org.wanna.jabbot.binding.config.RoomConfiguration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author vmorsiani <vmorsiani>
 * @since 2014-08-14
 */
public class CliRoom extends AbstractRoom<Object> implements Runnable {
	private final static Logger logger = LoggerFactory.getLogger(CliRoom.class);
	private RoomConfiguration configuration;
	private final List<BindingListener> listeners;


	public CliRoom(CliBinding connection,List<BindingListener> listeners) {
		super(connection);
		this.listeners = (listeners==null?new ArrayList<BindingListener>() : listeners);

	}

	@Override
	public void run()
	{
		System.out.println("CLI Room started");
		BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			try {
				String line=buffer.readLine();
				logger.debug("received {}",line);

				if(line == null) {
					logger.error("Got a null, probably no console, dying now");
					return;
				}

				for (BindingListener listener : listeners) {
					BindingMessage message = new BindingMessage(this.getRoomName(),"cli",line);
					listener.onMessage((CliBinding)connection,message);
				}
			} catch (IOException e) {
				logger.error("IO Error reading sdtin, dying");
				return;
			}
		}
	}

	@Override
	public boolean sendMessage(String message) {
		System.out.println(message);
		return true;
	}

	@Override
	public boolean join(final RoomConfiguration configuration) {
		this.configuration = configuration;
		new Thread(this).start();
		return true;
	}

	@Override
	public String getRoomName() {
		return configuration.getName();
	}
}

@@ -1121,66 +1121,70 @@
 ine=
-buffer.readLine();%0A%09%09%09%09logger.debug(%22received %7B%7D%22,l
+%22%22;%0A%09%09%09%09%0A%09%09%09%09while (true) %7B%0A%09%09%09%09%09line += buffer.readL
 ine
+(
 );%0A%0A
+%09
 %09%09%09%09
@@ -1198,24 +1198,25 @@
  == null) %7B%0A
+%09
 %09%09%09%09%09logger.
@@ -1269,24 +1269,25 @@
 now%22);%0A%09%09%09%09%09
+%09
 return;%0A%09%09%09%09
@@ -1286,17 +1286,183 @@
 rn;%0A%09%09%09%09
-%7D
+%09%7D%0A%0A%09%09%09%09%09if (line.endsWith(%22%5C%5C%22)) %7B%0A%09%09%09%09%09%09line = line.substring(0, line.length() - 1);%0A%09%09%09%09%09%7D else %7B%0A%09%09%09%09%09%09logger.debug(%22received %7B%7D%22,line);%0A%09%09%09%09%09%09break;%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D%0A
 %0A%0A%09%09%09%09fo

allow \ to be used for multi-line commands to be entered