package de.nerdclubtfg.signalbot;

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

import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
import org.whispersystems.signalservice.api.messages.multidevice.ReadMessage;

import de.nerdclubtfg.signalbot.components.Config;
import de.nerdclubtfg.signalbot.components.Signal;
import de.nerdclubtfg.signalbot.components.SignalConnection;
import de.nerdclubtfg.signalbot.components.SignalConsole;
import de.thoffbauer.signal4j.listener.ConversationListener;
import de.thoffbauer.signal4j.store.Group;
import de.thoffbauer.signal4j.store.User;

public class SignalBot implements ConversationListener {
	
	public void start(boolean offline) throws IOException {
		if(offline) {
			Signal.setInstance(new SignalConsole());
		} else {
			Signal.setInstance(new SignalConnection());
		}
		Config.load();
		
		Config config = Config.getInstance();
		for(Plugin plugin : Plugin.PLUGINS) {
			plugin.setEnabled(config.isEnabled(plugin));
		}
		
		Signal signal = Signal.getInstance();
		signal.addConversationListener(this);
		while(true) {
			try {
				signal.pull(60 * 1000);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onMessage(User sender, SignalServiceDataMessage message, Group group) {
		for(Plugin plugin : Plugin.PLUGINS) {
			try {
				if(plugin.isEnabled() && plugin.accepts(sender, group, message)) {
					plugin.onMessage(sender, group, message);
				}
			} catch(Exception e) {
				try {
					Signal.getInstance().sendMessage(sender, group, 
							SignalServiceDataMessage.newBuilder().withBody("Internal Error!"));
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws IOException {
		boolean offline = args.length != 0 && args[0].equals("offline");
		new SignalBot().start(offline);
	}

	@Override
	public void onContactUpdate(User contact) {}

	@Override
	public void onGroupUpdate(User sender, Group group) {}

	@Override
	public void onReadUpdate(List<ReadMessage> readList) {}
	
}

@@ -52,24 +52,52 @@
 OException;%0A
+import java.util.ArrayList;%0A
 import java.
@@ -1323,16 +1323,66 @@
 roup) %7B%0A
+%09%09ArrayList%3CString%3E executed = new ArrayList%3C%3E();%0A
 %09%09for(Pl
@@ -1409,24 +1409,24 @@
 .PLUGINS) %7B%0A
-
 %09%09%09try %7B%0A%09%09%09
@@ -1540,16 +1540,53 @@
 ssage);%0A
+%09%09%09%09%09executed.add(plugin.getName());%0A
 %09%09%09%09%7D%0A%09%09
@@ -1829,32 +1829,32 @@
 ntStackTrace();%0A
-
 %09%09%09%7D%0A%09%09%7D%0A%09%7D%0A%0A%09pu
@@ -1842,24 +1842,215 @@
 );%0A%09%09%09%7D%0A%09%09%7D%0A
+%09%09if(executed.size() %3E 0) %7B%0A%09%09%09System.out.println(sender.getNumber() + %22: %22 + message.getBody().or(%22no body%22).replace(%22%5Cn%22, %22%5C%5Cn%22)%0A%09%09%09%09%09+ %22 forwarded to %22 + String.join(%22, %22, executed));%0A%09%09%7D%0A
 %09%7D%0A%0A%09public 

Add logging of incoming messages