package bot;

import org.jibble.pircbot.*;
import java.lang.Math;
import java.awt.*;
import java.awt.image.*;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import javax.imageio.ImageIO;
import pack5.pack6.pack7.*;
import java.util.Properties;

public class IRCBot extends PircBot {
	
	public String username;
	public String hostname;
	public Client client;
	BufferedImage buf;
	Graphics2D g2d;
	
	public String screenshotPath = ".";
	public String nickPrefix = "rnd";
	public String dropBoxURL = "";
	public String forumuser = "";
	public boolean useDropBox = false;
	public boolean useCharName = false;
	public boolean updateModNearby = false;

	public IRCBot(Client cl) {
		super();
		try {
			Properties p = new Properties();
			p.load(new FileInputStream("settings.ini"));
			screenshotPath = p.getProperty("sspath");
			useCharName = p.getProperty("useign").equalsIgnoreCase("true");
			nickPrefix = p.getProperty("nickprefix");
			useDropBox = p.getProperty("usedropbox").equalsIgnoreCase("true");
			dropBoxURL = p.getProperty("dropboxurl");
			updateModNearby = p.getProperty("updatesswhenmodnearby").equalsIgnoreCase("true");
			forumuser = p.getProperty("forumuser");
				            if (forumuser.equals("")) {
                				System.out.println("Forum username not set in settings.ini");
                				System.exit(1);
                           				 } else {
                				System.out.println("Successfully authed user!");
            }
		}
		catch(Exception e) {System.out.println("Could not load settings.ini:");e.printStackTrace();}
		this.client = cl;
		this.username = nickPrefix + ((int)(Math.random() * 1000000 + 100));
		this.hostname = "irc.rizon.net";
		try {
			debug("Connecting to IRC with nick " + this.username);
			connect(hostname);
		} catch (Exception e) { debug("Failed to connect to IRC"); }
		buf = new BufferedImage(512, 345, BufferedImage.TYPE_INT_ARGB);
		g2d = buf.createGraphics();
	}
	public void debug(String s) {
		System.out.println("IRC: " + s);
	}
	public void onConnect() {
		debug("Now connected to IRC...");
		debug("Changing username to: " + username);
		changeNick(username);
		debug("Joining #autobots");
		joinChannel("#autobots", "niggarz");
	}
	
	public void onJoin(String channel, String nick, String login, String hostname) {
		if(nick.equals(username)) {
			debug("Joined channel #autobots");
			msg("04,1(00AUTOBOT 09v"+ client.version +"00 SIGNING IN04)");
		}
	}
	public void onMessage(String channel, String sender, String login, String hostname, String message) {
			boolean isOp;
       			User users[] = getUsers(channel);
       			isOp = false;
      			  for(int ii = 0; ii < users.length; ii++)
           		  if(users[ii].getNick().equalsIgnoreCase(sender) && users[ii].isOp())
           		     isOp = true;
			     if(!isOp)
			try {
			        
			if (message.substring(0,username.length()).equals(username)) {
				debug("Username caught");
				if (client.loggedIn()) {
					if(message.substring(username.length(), username.length() + 1).equals(":"))
						message = message.split(":")[0] + message.split(":")[1];
					String msg = message.substring(username.length() + 1);
					msg = msg.trim();
					if (msg.substring(0,2).equals("::")) {
						if(msg.equals("::view") || msg.equals("::ss")) {
							g2d.drawImage(client.aClass26_Sub1_1195.anImage176, 0, 0, client);
							long millis = System.currentTimeMillis();
							writeImageOut();
							return;
						}
						else if (msg.equals("::stuck")) {
							client.method38("stuck");
							msg("04,1[09" + client.getUsername() + "04] (U00sed 09::stuck04)");
						}
						else if(msg.equals("::exit")) {
						     	    client.method75();
						            System.exit(0);
						}
						else if (msg.equals("::pause")) {
							client.paused = true;
							msg("04,1[09" + client.getUsername() + "04] (S00cripts 09paused04)");
						}
						else if (msg.equals("::resume")) {
							client.paused = false;
							msg("04,1[09" + client.getUsername() + "04] (S00cripts 09resumed04)");
						}
						else if (msg.equals("::username") || msg.equals("::name")) {
							msg("04,1Username: 09" + client.getUsername());
						}
						else if (msg.equals("::reset")) {
							client.dontSleep = false;
							client.paused = false;
							msg("04,1[09" + client.getUsername() + "04] F00atiguing has been reset");
						}
						else if(msg.equals("::where") || msg.equals("::loc") || msg.equals("::location")) {
							msg("04,1[09" + client.getUsername() +"4]00 is at 09" + client.whereAmI());
						}
						else if(msg.equals("::walkn")) { 
						            client.walkTo(client.GetX(), client.GetY() - 1);
						            msg("04,1[09" + client.getUsername() +"4]00 is walking 09north");
						            }
						else if(msg.equals("::walks")) { 
						            client.walkTo(client.GetX(), client.GetY() + 1);
						            msg("04,1[09" + client.getUsername() +"4]00 is walking 09south");
						            }
						else if(msg.equals("::walke")) { 
						            client.walkTo(client.GetX() - 1, client.GetY());
						            msg("04,1[09" + client.getUsername() +"4]00 is walking 09east");
						            }
						else if(msg.equals("::walkw")) { 
						            client.walkTo(client.GetX() + 1, client.GetY());
						            msg("04,1[09" + client.getUsername() +"4]00 is walking 09west");
						            }
						else  if(msg.substring(0, 5).equals("::msg")) {
            						client.sendPm(msg.split(" ")[1].replace("_", " "), msg.substring(msg.split(" ")[1].length() + 7));
            						 msg("04,1[09" + client.getUsername() +"4]0You tell 09 " + msg.split(" ")[1] + (": 08") + msg.substring(msg.split(" ")[1].length() + 7));
            					}
						else if(msg.equals("::stats")) {
							String str = "";
							for(int i = 0; i < client.noOfStats(); i++) {
								str += "00" + client.statShorts[i] + ":" + "09" + client.getStatCurrent(i) + "/" + client.getStatBase(i);
								if(i != client.noOfStats() - 1)
									str += "04, ";
							}
							msg("04,1[09" + client.getUsername() + "04] S00tats: 09" + str);
						}
						else if(msg.equals("::players")) {
							String str = "";
							for(int i = 0; i < client.anInt976; i++) {
								if(client.aClass31Array1171[i].aString294.equalsIgnoreCase(client.getUsername()))
									continue;
								str += "09" + client.aClass31Array1171[i].aString294 + "(" + client.aClass31Array1171[i].anInt314 + (client.aClass31Array1171[i].anInt326 == 1 ? "S" : "") + ")";
								if(i != client.anInt976 - 1)
									str += "04" + ", ";
							}
							if(str.equals(""))
								msg("04,1[09" + client.getUsername() + "04] N00o other players nearby");
							else
								msg("04,1[09" + client.getUsername() + "04] P00layers near: 09" + str);
							
						}
						else if(msg.equals("::info")) {
							int combat = (client.getStatBase(0) + client.getStatBase(1) + client.getStatBase(2) + client.getStatBase(3)) / 4;
							String send = "04C00B:09" + combat + " 04| S00CRIPT:09 " + client.lastScript + "04, A00RGS:09" + client.lastArgs;
							msg("04,1[09" + client.getUsername() + "04] " + send);
						}
						else if(msg.equals("::autologin") || msg.equals("::autolog")) {
							client.autologin = !client.autologin;
							msg("04,1[09" + client.getUsername() + "04] A00utologin turned 09" + (client.autologin ? "on" : "off"));
						}
						else if(msg.equals("::logout")) {
							if(client.anInt1015 == 0)
								return;
							if(client.anInt949 > 450) {
								msg("04,1[09" + client.getUsername() + "4] C00an't logout during combat!");
								return;
							}
							if(client.anInt949 > 0) {
								msg("04,1[09" + client.getUsername() + "4] C00an't logout for 10 seconds after combat");
								return;
							}
							else {
								msg("04,1[09" + client.getUsername() + "04] L00ogged out");
								client.autologin = false;
								// let's not send packets here, call the method in client instead
								client.method75();
							}
						}
						else {
							//String ret = client.methods.getCommand(msg);
							String ret = client.methods.onIrcCommand(msg.substring(2));
							if(ret == null)
								return;
							msg("04,1[09" + client.getUsername() + "04] 00" + ret);
						}
					}
					else {
						client.speak(msg);
						msg("04,1"  + "[09" + client.getUsername() + "4] 04S00ent message:09 " + msg);
					}
				}
				else {
					msg("04,1" + "Client not 09" + "LOGGEDIN");
				}
			}
		} catch (Exception e) { }
	}
	public void writeImageOut()
   		 {
      		  try
       		 {
            URL url = new URL("http://autobots.biz/view.php");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            g2d.drawImage(client.aClass26_Sub1_1195.anImage176, 0, 0, client);
            ImageIO.write(buf, "png", conn.getOutputStream());
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            do
            {
                String link;
                if((link = rd.readLine()) == null)
                    break;
                if(!link.equals("ERROR"))
                    msg((new StringBuilder()).append("\00304,1\002[\00309").append(client.getUsername()).append("\00304] S\00300creenshot at \00309").append(link).toString());
            } while(true);
            rd.close();
        }
        catch(Exception e)
        {
            client.debug("Failed to upload ScreenShot");
        }
    }

	
	public void onLogin() {
		if(useCharName) {
			this.username = client.getUsername().replace(" ","_") + "-BOT";
			changeNick(this.username);
		}
	}
	
	public void msg(String s) {
		sendMessage("#autobots", s);
	}
	
	public void modChatDetected(String name, String s) {
		msg("04,1[09" + client.getUsername() + "04] M00OD CHATTING 04(09" + client.whereAmI() + "04) (09" + name + "04):09 " + s);
	}
	
	public long backthen = System.currentTimeMillis();
	
	/*public void modInArea(int modstatus, String name) {
		long now = System.currentTimeMillis();
		if(now - backthen > 5000L) {
			if(useDropBox && updateModNearby) {
				try {
					g2d.drawImage(client.aClass26_Sub1_1195.anImage176, 0, 0, client);
					ImageIO.write(buf, "png", new File (screenshotPath + "/mod.png"));
				}
				catch(Exception e) {}
				//msg(Colors.RED + "[" + Colors.GREEN + client.getUsername() + Colors.RED + "] " + Colors.NORMAL + "MOD DETECTED (" + Colors.TEAL + client.whereAmI() + Colors.NORMAL + "): " + Colors.GREEN + name + Colors.NORMAL + " - " + Colors.TEAL + dropBoxURL + "mod.png");
			}
			else
				//msg(Colors.RED + "[" + Colors.GREEN + client.getUsername() + Colors.RED + "] " + Colors.NORMAL + "MOD DETECTED (" + Colors.TEAL + client.whereAmI() + Colors.NORMAL + "): " + Colors.GREEN + name);
			backthen = System.currentTimeMillis();
		}
	}*/
	
	public void irrationalFatigueDetected() {
		msg("04,1[09" + client.getUsername() + "04] I00RRATIONAL FATIGUE DETECTED - USE 09::reset00 AFTER DEALING WITH MODS");
	}
	
	public void irrationalSleepDetected() {
		msg("04,1[09" + client.getUsername() + "04] I00RRATIONAL SLEEP DETECTED");
	}
	
	public void playerSaid(String s) {
		msg("04,1[09" + client.getUsername() + "04]00 " + client.getUsername() + "04(09client04):00 " + s);
	}
	
}
