package de.blackcraze.grb.commands;

import static de.blackcraze.grb.util.CommandUtils.getResponseLocale;
import static de.blackcraze.grb.util.PrintUtils.prettyPrint;
import static org.bytedeco.javacpp.Pointer.deallocateReferences;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import de.blackcraze.grb.core.Speaker;
import de.blackcraze.grb.core.BotConfig;
import de.blackcraze.grb.i18n.Resource;
import de.blackcraze.grb.ocr.OCR;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.Message.Attachment;

public class FileProcessor {

	public static void ocrImages(Message message) {
		for (Attachment att : message.getAttachments()) {
			if (att.isImage()) {
				Locale locale = getResponseLocale(message);
				InputStream stream = null;
				try {
					URLConnection conn = new URL(att.getProxyUrl()).openConnection();
					conn.setRequestProperty("User-Agent",
							"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
					conn.connect();

                    stream = new BufferedInputStream(conn.getInputStream());
					Map<String, Long> stocks = OCR.getInstance().convertToStocks(stream, locale);
					
					/* decide if the result is printed into the channel */
					if (BotConfig.getConfig(message.getGuild()).ocrResult == "on") {
						Speaker.sayCode(message.getTextChannel(), prettyPrint(stocks, locale));
					}
					
					Commands.internalUpdate(message, locale, stocks);
				} catch (Throwable e) {
					Speaker.err(message, String.format(Resource.getString("ERROR_UNKNOWN", locale), e.getMessage()));
					e.printStackTrace();
				} finally {
				    IOUtils.closeQuietly(stream);
					deallocateReferences();
				}
			}
		}
		
		/* try to delete the message containing the upload images or add a "finished" reaction */
		if (BotConfig.getConfig(message.getGuild()).remPictureMessage == "on") {
			message.delete().queue();			
		} else {
			message.addReaction(Speaker.Reaction.COMPLETE).queue();
		}
	}

}

@@ -1510,25 +1510,40 @@
 crResult
- == 
+.equalsIgnoreCase(
 %22on%22)
+)
  %7B%0D%0A%09%09%09%09
@@ -2116,17 +2116,32 @@
 sage
- == 
+.equalsIgnoreCase(
 %22on%22)
+)
  %7B%0D%0A
@@ -2163,20 +2163,9 @@
 te()
-.queue();%09%09%09
+;
 %0D%0A%09%09

use euals function