package org.kaospvp.main;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.Instrument;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Note;
import org.bukkit.Note.Tone;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.PrepareItemCraftEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.util.Vector;

// mckaospvp.ddns.net

public class Core extends JavaPlugin implements Listener {
	
	private static final String tag = ChatColor.GOLD + "[" + ChatColor.GREEN + "KaosPvP" + ChatColor.GOLD + "] ";
	
	private static Location jailLoc = new Location(Bukkit.getWorld("kaospvp"), 1106, 32, -236); // hard coded :(
	private static Location jailLeaveLoc = new Location(Bukkit.getWorld("kaospvp"), 1103, 33, -238); // hard coded :(
	public boolean musicEnabled = true;
	@Override
	public void onEnable() {
		Bukkit.getServer().getPluginManager().registerEvents(this, this);
		if(! this.getDataFolder().exists()){
			this.getDataFolder().mkdir();
		}
		Punished.setDataFolder(this.getDataFolder().getPath());
		Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
			public void run(){
				clearJunk();
			}
		}, 0L, 10);
		Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
			public void run(){
				if(musicEnabled){
					restartMusic();
				}
			}
		}, 0L, 20*((3*60)+10));
		getLogger().info("Kaospvp essentials are now online!!!");
		getLogger().info("                :D                  ");
	}
	public void restartMusic(){
		Bukkit.getWorld("kaospvp").playEffect(Bukkit.getWorld("kaospvp").getSpawnLocation(), Effect.RECORD_PLAY, 0);
		Bukkit.getWorld("kaospvp").playEffect(Bukkit.getWorld("kaospvp").getSpawnLocation(), Effect.RECORD_PLAY, Material.RECORD_9);
	}
	public void stopMusic(){
		Bukkit.getWorld("kaospvp").playEffect(Bukkit.getWorld("kaospvp").getSpawnLocation(), Effect.RECORD_PLAY, 0);
	}
	public void startMusic(){
		Bukkit.getWorld("kaospvp").playEffect(Bukkit.getWorld("kaospvp").getSpawnLocation(), Effect.RECORD_PLAY, Material.RECORD_9);
	}
	@Override
	public void onDisable() {
		getLogger().info("Kaospvp essentials are no longer offline!");
		getLogger().info("kaospvp essentials has shutdown!");
	}

	@EventHandler(priority=EventPriority.HIGHEST)
	public void onHit(EntityDamageByEntityEvent e) {
		if(e.isCancelled())return;
		if (e.getEntity() instanceof Player && e.getDamager() instanceof Player) {
			// Player to = (Player) e.getEntity();
			Player by = (Player) e.getDamager();
			if (!e.isCancelled()) {
				by.giveExp(5);
			}
		}
	}
	
	private List<String> pwm = new ArrayList<String>(); // players watching messages
	private List<String> pwli = new ArrayList<String>(); // players watching log info
	private List<String> prt = new ArrayList<String>(); // players reply to ?
	
	// command handeling
	@SuppressWarnings("deprecation")
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
		if(cmd.getName().equalsIgnoreCase("rules")){
			sender.sendMessage(tag + ChatColor.GRAY + "------ Rules ------");
			sender.sendMessage(ChatColor.RED + "[1] " + ChatColor.BLUE + " No Hacking, Cheating or Glitching");
			sender.sendMessage(ChatColor.RED + "[2] " + ChatColor.BLUE + " Don't Hackusate, Use /report");
			sender.sendMessage(ChatColor.RED + "[3] " + ChatColor.BLUE + " Respect Other Players");
			sender.sendMessage(ChatColor.RED + "[4] " + ChatColor.BLUE + " Don't Swear");
			sender.sendMessage(ChatColor.RED + "[5] " + ChatColor.BLUE + " Don't Spam");
			sender.sendMessage(ChatColor.RED + "[6] " + ChatColor.BLUE + " Only English in main chat");
			sender.sendMessage(ChatColor.BLUE + "    (Other languages are allowed in /msg)");
			sender.sendMessage(ChatColor.RED + "[7] " + ChatColor.BLUE + " No Third Party Advertising!");
			sender.sendMessage(ChatColor.RED + "[8] " + ChatColor.BLUE + " No Discrimination Against Anyone (1 month mute)");
			sender.sendMessage(tag + ChatColor.GRAY + "------ Rules ------");
			sender.sendMessage(ChatColor.BLUE + "If you have any issues that you cannot");
			sender.sendMessage(ChatColor.BLUE + "resolve then talk to " + ChatColor.RED + "OverloadedCore#0590");
			sender.sendMessage(ChatColor.BLUE + "On Discord! Thank you for reading.");
			return true;
		}
		
		if(cmd.getName().equalsIgnoreCase("trash")){
			if(sender instanceof Player){
				Inventory inv = Bukkit.createInventory(null, 45, "Dispose of items in here");
				((Player) sender).openInventory(inv);
			}else{
				sender.sendMessage(tag + ChatColor.RED + "Only players can use the trash!");
			}
			return true;
		}
		
///////////////////////////////////////////// Messaging System ///////////////////////////////////
		
		if(cmd.getName().equalsIgnoreCase("msg")){
			if(sender instanceof Player){
				Player p = (Player) sender;
				if(args.length < 2){
					p.sendMessage(tag + ChatColor.RED + "Usage:");
					p.sendMessage(ChatColor.GOLD + "/msg <player> <message>");
					return true;
				}else{
					if(isPOnline(args[0])){
						Player to = Bukkit.getPlayer(args[0]);
						String msgtosend = "";
						for(int i = 1; i < args.length; i++){
							msgtosend = msgtosend + args[i] + " ";
						}
						to.sendMessage(ChatColor.DARK_GREEN + "[" + ChatColor.RED + p.getName() + ChatColor.DARK_GREEN
								+ " -> " + ChatColor.RED + "me" + ChatColor.DARK_GREEN + "] " + ChatColor.GRAY +
								msgtosend);
						pstp(to);
						p.sendMessage(ChatColor.DARK_GREEN + "[" + ChatColor.RED + "me" + ChatColor.DARK_GREEN
								+ " -> " + ChatColor.RED + to.getName() + ChatColor.DARK_GREEN + "] " + ChatColor.GRAY +
								msgtosend);
						
						for(String pfats : pwm){
							Player pp = Bukkit.getPlayer(pfats);
							if(! ( p.getName().equals(pp.getName()) || to.getName().equals(pp.getName())))
								pp.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GRAY + p.getName() + ChatColor.DARK_GRAY
									+ " -> " + ChatColor.GRAY + to.getName() + ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
									msgtosend);
						}
						setPlayerReplyName(p.getName(), to.getName());
						setPlayerReplyName(to.getName(), p.getName());
						return true;
					}else{
						p.sendMessage(tag + ChatColor.RED + "That player isn\'t online.");
						return true;
					}
				}
			}else{
				sender.sendMessage(tag + ChatColor.RED + "Only players can use private messages");
				return true;
			}
		}
		if(cmd.getName().equalsIgnoreCase("r")){
			if(sender instanceof Player){
				Player p = (Player) sender;
				if(args.length < 1){
					p.sendMessage(tag + ChatColor.RED + "Usage:");
					p.sendMessage(ChatColor.GOLD + "/r <message>");
					return true;
				}else{
					String ptm = getReplyName(p.getName());
					if(ptm == null){
						p.sendMessage(tag + ChatColor.RED + "You have no-one to reply to.");
						return true;
					}
					if(isPOnline(ptm)){
						Player to = Bukkit.getPlayer(ptm);
						String msgtosend = "";
						for(int i = 0; i < args.length; i++){
							msgtosend = msgtosend + args[i] + " ";
						}
						to.sendMessage(ChatColor.DARK_GREEN + "[" + ChatColor.RED + p.getName() + ChatColor.DARK_GREEN
								+ " -> " + ChatColor.RED + "me" + ChatColor.DARK_GREEN + "] " + ChatColor.GRAY +
								msgtosend);
						pstp(to);
						p.sendMessage(ChatColor.DARK_GREEN + "[" + ChatColor.RED + "me" + ChatColor.DARK_GREEN
								+ " -> " + ChatColor.RED + to.getName() + ChatColor.DARK_GREEN + "] " + ChatColor.GRAY +
								msgtosend);
						
						for(String pfats : pwm){ // part for admins to see
							Player pp = Bukkit.getPlayer(pfats);
							if(! ( p.getName().equals(pp.getName()) || to.getName().equals(pp.getName())))
								pp.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GRAY + p.getName() + ChatColor.DARK_GRAY
									+ " -> " + ChatColor.GRAY + to.getName() + ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
									msgtosend);
						}
						setPlayerReplyName(to.getName(), p.getName());
						return true;
					}else{
						p.sendMessage(tag + ChatColor.RED + "That player isn\'t online.");
						return true;
					}
				}
			}else{
				sender.sendMessage(tag + ChatColor.RED + "Only players can use private messages");
				return true;
			}
		}
		
///////////////////////////////////////////// End of Messaging System ////////////////////////////
		
		if(cmd.getName().equalsIgnoreCase("staff")){
			if(sender.hasPermission("kaos.staff") || sender.hasPermission("*") || sender.hasPermission("kaos.owner")){
				if(args.length < 1){
					sender.sendMessage(tag + ChatColor.BLUE + "Kaos Staffing");
					sender.sendMessage(ChatColor.GRAY + "do " + ChatColor.RED + "/staff help" + ChatColor.GRAY + " for help.");
				}else{
					if(args[0].equalsIgnoreCase("h") || args[0].equalsIgnoreCase("help")){
						sender.sendMessage(tag + ChatColor.BLUE + "Kaos Staffing");
						sender.sendMessage(ChatColor.RED + "/staff h/help " + ChatColor.GRAY + "Display Help for Staff Command.");
						sender.sendMessage(ChatColor.RED + "/staff p/punish " + ChatColor.GRAY + "Punish player.");
						sender.sendMessage(ChatColor.RED + "/staff unmute " + ChatColor.GRAY + "Un-mute a player.");
						sender.sendMessage(ChatColor.RED + "/staff unban " + ChatColor.GRAY + "Un-ban a player.");
						sender.sendMessage(ChatColor.RED + "/staff unjail " + ChatColor.GRAY + "Un-jail a player.");
						sender.sendMessage(ChatColor.RED + "/staff am " + ChatColor.GRAY + "Broadcast Anonymous Staff Message.");
						sender.sendMessage(ChatColor.RED + "/staff c/chat " + ChatColor.GRAY + "Staff Only Chat.");
						sender.sendMessage(ChatColor.RED + "/staff mw/msgwatch " + ChatColor.GRAY + "Toggle ability to view private messages");
						sender.sendMessage(ChatColor.RED + "/staff w/watch " + ChatColor.GRAY + "Toggle watch mode.");
						sender.sendMessage(ChatColor.RED + "/staff pli/playerloginfo " + ChatColor.GRAY + "See when players log.");
					}else if(args[0].equalsIgnoreCase("p") || args[0].equalsIgnoreCase("punish")){
						if(args.length < 3){
							sender.sendMessage(tag + ChatColor.BLUE + "Kaos Staffing");
							sender.sendMessage(ChatColor.GRAY + "Use command like: " + ChatColor.RED + "/staff punish <player> <reasonID> [flags]");
							sender.sendMessage(ChatColor.GRAY + "Reasons and IDs are:");
							sender.sendMessage(ChatColor.RED + "chat/1" + ChatColor.GRAY + ": General Chat");
							sender.sendMessage(ChatColor.RED + "schat/1.2" + ChatColor.GRAY + ": Severe Chat Misbehaviour");
							sender.sendMessage(ChatColor.RED + "discrimination/2" + ChatColor.GRAY + ": Discrimination/Derogatory Chat");
							sender.sendMessage(ChatColor.RED + "advertising/3" + ChatColor.GRAY + ": Advertising");
							sender.sendMessage(ChatColor.RED + "cheating/4" + ChatColor.GRAY + ": Cheating/Glitching");
							sender.sendMessage(ChatColor.RED + "botting/5" + ChatColor.GRAY + ": Using Bots");
							if(sender.hasPermission("kaos.owner")){
								sender.sendMessage(ChatColor.RED + "ddos/101" + ChatColor.GRAY + ": DDoSing the server or staff");
								sender.sendMessage(ChatColor.RED + "prick/102" + ChatColor.GRAY + ": Being a prick");
								sender.sendMessage(ChatColor.RED + "crashing/103" + ChatColor.GRAY + ": Lagging/Crashing The Server");
								sender.sendMessage(ChatColor.RED + "doxing/104" + ChatColor.GRAY + ": Doxing");
							}
						}else{
							if(Bukkit.getOfflinePlayer(args[1]).hasPlayedBefore() || Bukkit.getPlayer(args[1]) != null){
								boolean ipo =
										Bukkit.getPlayer(args[1]) == null ? 
										false : true; // is player online?
								String uuid = !ipo ? 
										Bukkit.getOfflinePlayer(args[1]).getUniqueId().toString() :
										Bukkit.getPlayer(args[1]).getUniqueId().toString();
								List<String> flags = new ArrayList<String>();
								for(int ij = 3; ij < args.length; ij++){
									flags.add(args[ij]);
								}
								switch(args[2].toLowerCase()){
									case "chat":
									case "1":
										Punished.setMuted(uuid, (1000 * 60 * 10), "Chat"); // 10 minute mute
										if(!(flags.contains("--silent") || flags.contains("-s")))
											Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(),
													"bc " + sender.getName() + " has muted " + args[1] + " for chat");
										if(ipo){
											Bukkit.getPlayer(args[1]).sendMessage(tag + ChatColor.RED + "You have been muted for chat!");
										}
										for(Player p : Bukkit.getServer().getOnlinePlayers()){
											if(p.hasPermission("kaos.staff")){
												p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
														+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
														"" + sender.getName() + " has muted " + args[1] + " for chat");
											}
										}
										break;
									case "schat":
									case "1.2":
										Punished.setMuted(uuid, (1000*60*60*100), "Severe Chat"); // 10 minute mute
										if(!(flags.contains("--silent") || flags.contains("-s")))
											Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(),
													"bc " + sender.getName() + " has muted " + args[1] + " for severe chat");
										if(ipo){
											Bukkit.getPlayer(args[1]).sendMessage(tag + ChatColor.RED + "You have been muted for Severe Chat!");
										}
										for(Player p : Bukkit.getServer().getOnlinePlayers()){
											if(p.hasPermission("kaos.staff")){
												p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
														+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
														"" + sender.getName() + " has muted " + args[1] + " for severe chat");
											}
										}
										break;
									case "discrimination":
									case "2":
										Punished.setMuted(uuid, (long)1000*60*60*24*30, "Discrimination");
										if(!(flags.contains("--silent") || flags.contains("-s")))
											Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(),
													"bc " + sender.getName() + " has muted " + args[1] + " for discrimination");
										if(ipo){
											Bukkit.getPlayer(args[1]).sendMessage(tag + ChatColor.RED + "You have been muted for Discrimination!");
										}
										for(Player p : Bukkit.getServer().getOnlinePlayers()){
											if(p.hasPermission("kaos.staff")){
												p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
														+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
														"" + sender.getName() + " has muted " + args[1] + " for discrimination");
											}
										}
										break;
									case "advertising":
									case "3":
										Punished.setBanned(uuid, (long)1000*60*60*24*14, "Advertising");
										if(!(flags.contains("--silent") || flags.contains("-s")))
											Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(),
													"bc " + sender.getName() + " has banned " + args[1] + " for advertising");
										if(ipo){
											Bukkit.getPlayer(args[1]).kickPlayer(tag + ChatColor.RED + "Banned for advertising!");
										}
										for(Player p : Bukkit.getServer().getOnlinePlayers()){
											if(p.hasPermission("kaos.staff")){
												p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
														+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
														"" + sender.getName() + " has banned " + args[1] + " for advertising");
											}
										}
										break;
									case "cheating":
									case "4":
										Punished.setBanned(uuid, (long)1000*60*60*24*30, "Cheating");
										if(!(flags.contains("--silent") || flags.contains("-s")))
											Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(),
													"bc " + sender.getName() + " has banned " + args[1] + " for cheating");
										if(ipo){
											Bukkit.getPlayer(args[1]).kickPlayer(tag + ChatColor.RED + "Banned for cheating!");
										}
										for(Player p : Bukkit.getServer().getOnlinePlayers()){
											if(p.hasPermission("kaos.staff")){
												p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
														+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
														"" + sender.getName() + " has banned " + args[1] + " for cheating");
											}
										}
										break;
									case "botting":
									case "5":
										if(ipo){
											Punished.setJailed(uuid, (long)1000*60*60*24*14, "Using Bots");
											if(!(flags.contains("--silent") || flags.contains("-s")))
												Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(),
														"bc " + sender.getName() + " has jailed " + args[1] + " for botting");
											Player player = Bukkit.getPlayer(args[1]);
											player.setHealth(20);
											player.getInventory().clear();
											jailLoc = new Location(Bukkit.getWorld("kaospvp"), 1106, 32, -236);
											jailLeaveLoc = new Location(Bukkit.getWorld("kaospvp"), 1103, 33, -238);
											player.teleport(jailLoc);
											player.sendMessage(tag + ChatColor.RED + "You have been jailed for botting!");
											for(Player p : Bukkit.getServer().getOnlinePlayers()){
												if(p.hasPermission("kaos.staff")){
													p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
															+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
															"" + sender.getName() + " has jailed " + args[1] + " for botting");
												}
											}
										}else{
											sender.sendMessage(tag + ChatColor.RED + "You can only jail online players!");
										}
										break;
									case "ddos":
									case "101":
										if(sender.hasPermission("kaos.owner")){
											Punished.setBanned(uuid, (long)1000*60*60*24*365*25, "DDoS");
											if(!(flags.contains("--silent") || flags.contains("-s")))
												Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(),
														"bc " + sender.getName() + " has banned " + args[1] + " for ddos");
											if(ipo){
												Bukkit.getPlayer(args[1]).kickPlayer(tag + ChatColor.RED + "Banned for DDoS!");
											}
											for(Player p : Bukkit.getServer().getOnlinePlayers()){
												if(p.hasPermission("kaos.staff")){
													p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
															+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
															"" + sender.getName() + " has banned " + args[1] + " for DDoS");
												}
											}
										}else{
											sender.sendMessage(tag + ChatColor.RED + "This is an owner only punishment!");
										}
										break;
									case "prick":
									case "102":
										if(sender.hasPermission("kaos.owner")){
											if(ipo){
												Punished.setJailed(uuid, (long)1000*60*60*1, "Being a prick");
												if(!(flags.contains("--silent") || flags.contains("-s")))
													Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(),
															"bc " + sender.getName() + " has jailed " + args[1] + " for being a prick");
												Player player = Bukkit.getPlayer(args[1]);
												player.setHealth(20);
												player.getInventory().clear();
												jailLoc = new Location(Bukkit.getWorld("kaospvp"), 1106, 32, -236);
												jailLeaveLoc = new Location(Bukkit.getWorld("kaospvp"), 1103, 33, -238);
												player.teleport(jailLoc);
												player.sendMessage(tag + ChatColor.RED + "You have been jailed for being a prick!");
												for(Player p : Bukkit.getServer().getOnlinePlayers()){
													if(p.hasPermission("kaos.staff")){
														p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
																+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
																"" + sender.getName() + " has jailed " + args[1] + " for being a prick");
													}
												}
											}else{
												sender.sendMessage(tag + ChatColor.RED + "You can only jail online players!");
											}
										}else{
											sender.sendMessage(tag + ChatColor.RED + "This is an owner only punishment!");
										}
										break;
									case "crashing":
									case "103":
										if(sender.hasPermission("kaos.owner")){
											if(ipo){
												Punished.setJailed(uuid, (long)1000*60*60*24*2, "Lagging/Crashing the server");
												if(!(flags.contains("--silent") || flags.contains("-s")))
													Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(),
															"bc " + sender.getName() + " has jailed " + args[1] + " for lagging/crashing the server");
												Player player = Bukkit.getPlayer(args[1]);
												player.setHealth(20);
												player.getInventory().clear();
												jailLoc = new Location(Bukkit.getWorld("kaospvp"), 1106, 32, -236);
												jailLeaveLoc = new Location(Bukkit.getWorld("kaospvp"), 1103, 33, -238);
												player.teleport(jailLoc);
												player.sendMessage(tag + ChatColor.RED + "You have been jailed for lagging/crashing the server!");
												for(Player p : Bukkit.getServer().getOnlinePlayers()){
													if(p.hasPermission("kaos.staff")){
														p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
																+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
																"" + sender.getName() + " has jailed " + args[1] + " for lagging/crashing the server");
													}
												}
											}else{
												sender.sendMessage(tag + ChatColor.RED + "You can only jail online players!");
											}
										}else{
											sender.sendMessage(tag + ChatColor.RED + "This is an owner only punishment!");
										}
										break;
									case "doxing":
									case "104":
										if(sender.hasPermission("kaos.owner")){
											Punished.setBanned(uuid, (long)1000*60*60*24*365*25, "Doxing");
											if(!(flags.contains("--silent") || flags.contains("-s")))
												Bukkit.getServer().dispatchCommand(getServer().getConsoleSender(),
														"bc " + sender.getName() + " has banned " + args[1] + " for doxing");
											if(ipo){
												Bukkit.getPlayer(args[1]).kickPlayer(tag + ChatColor.RED + "Banned for Doxing!");
											}
											for(Player p : Bukkit.getServer().getOnlinePlayers()){
												if(p.hasPermission("kaos.staff")){
													p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
															+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
															"" + sender.getName() + " has banned " + args[1] + " for Doxing");
												}
											}
										}else{
											sender.sendMessage(tag + ChatColor.RED + "This is an owner only punishment!");
										}
										break;
									default:
										sender.sendMessage(tag + ChatColor.RED + "Invalid reason ID!");
										return true;
								}
							}else{
								sender.sendMessage(tag + ChatColor.RED + "Could not find player");
							}
						}
					}else if(args[0].equalsIgnoreCase("am")){
						if(args.length < 2){
							sender.sendMessage(tag + ChatColor.BLUE + "Kaos Staffing");
							sender.sendMessage(ChatColor.GRAY + "do " + ChatColor.RED + "/staff am <message>");
						}else{
							String msgtosend = "";
							for(int i = 1; i < args.length; i++){
								msgtosend = msgtosend + args[i] + " ";
							}
							Bukkit.getServer().broadcastMessage(tag + ChatColor.LIGHT_PURPLE + ChatColor.ITALIC + "[Staff]: " + msgtosend);
						}
					}else if(args[0].equalsIgnoreCase("c") || args[0].equalsIgnoreCase("chat")){
						if(args.length < 2){
							sender.sendMessage(tag + ChatColor.BLUE + "Kaos Staffing");
							sender.sendMessage(ChatColor.GRAY + "do " + ChatColor.RED + "/staff chat <message>");
						}else{
							String msgtosend = "";
							for(int i = 1; i < args.length; i++){
								msgtosend = msgtosend + args[i] + " ";
							}
							for(Player p : Bukkit.getServer().getOnlinePlayers()){
								if(p.hasPermission("kaos.staff")){
									p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + sender.getName()
											+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY + msgtosend);
								}
							}
							getLogger().info("\n" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + sender.getName()
											+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY + msgtosend);
						}
					}else if(args[0].equalsIgnoreCase("unmute")) {
						if(args.length != 2){
							sender.sendMessage(tag + ChatColor.BLUE + "Kaos Staffing");
							sender.sendMessage(ChatColor.GRAY + "do " + ChatColor.RED + "/staff unmute <player>");
						}else{
							if(Bukkit.getOfflinePlayer(args[1]).hasPlayedBefore() || Bukkit.getPlayer(args[1]) != null){
								boolean ipo =
										Bukkit.getPlayer(args[1]) == null ? 
										false : true; // is player online?
								String uuid = !ipo ? 
										Bukkit.getOfflinePlayer(args[1]).getUniqueId().toString() :
										Bukkit.getPlayer(args[1]).getUniqueId().toString();
								Punished.setMuted(uuid, (long)0, "unmute");
								if(ipo){
									Bukkit.getPlayer(args[1]).sendMessage(tag + ChatColor.GREEN + "You have been unmuted");
								}
								for(Player p : Bukkit.getServer().getOnlinePlayers()){
									if(p.hasPermission("kaos.staff")){
										p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
												+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
												"" + sender.getName() + " has unmuted " + args[1]);
									}
								}
							}else{
								sender.sendMessage(tag + ChatColor.RED + "Could not find player");
							}
						}
					}else if(args[0].equalsIgnoreCase("unban")) {
						if(args.length != 2){
							sender.sendMessage(tag + ChatColor.BLUE + "Kaos Staffing");
							sender.sendMessage(ChatColor.GRAY + "do " + ChatColor.RED + "/staff unban <player>");
						}else{
							if(Bukkit.getOfflinePlayer(args[1]).hasPlayedBefore() || Bukkit.getPlayer(args[1]) != null){
								boolean ipo =
										Bukkit.getPlayer(args[1]) == null ? 
										false : true; // is player online?
								String uuid = !ipo ? 
										Bukkit.getOfflinePlayer(args[1]).getUniqueId().toString() :
										Bukkit.getPlayer(args[1]).getUniqueId().toString();
								Punished.setBanned(uuid, (long)0, "unban");
								for(Player p : Bukkit.getServer().getOnlinePlayers()){
									if(p.hasPermission("kaos.staff")){
										p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
												+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
												"" + sender.getName() + " has unbanned " + args[1]);
									}
								}
							}else{
								sender.sendMessage(tag + ChatColor.RED + "Could not find player");
							}
						}
					}else if(args[0].equalsIgnoreCase("unjail")){
						if(args.length != 2){
							sender.sendMessage(tag + ChatColor.BLUE + "Kaos Staffing");
							sender.sendMessage(ChatColor.GRAY + "do " + ChatColor.RED + "/staff unjail <player>");
						}else{
							if(Bukkit.getPlayer(args[1]) != null){
								Player p = Bukkit.getPlayer(args[1]);
								p.teleport(p.getWorld().getSpawnLocation());
								String uuid = p.getUniqueId().toString();
								Punished.setJailed(uuid, (long)0, "unjail");
								p.sendMessage(tag + ChatColor.GREEN + "You have been unjailed");
								for(Player pp : Bukkit.getServer().getOnlinePlayers()){
									if(pp.hasPermission("kaos.staff")){
										pp.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
												+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
												"" + sender.getName() + " has unjailed " + args[1]);
									}
								}
							}else{
								sender.sendMessage(tag + ChatColor.RED + "You can only unjail online players!");
							}
						}
					}else if(args[0].equalsIgnoreCase("mw") || args[0].equalsIgnoreCase("msgwatch")) {
						if(sender instanceof Player){
							Player p = (Player) sender;
							if( pwm.contains(p.getName()) ){
								pwm.remove(p.getName());
								p.sendMessage(tag + ChatColor.BLUE + "Msgwatch for your account has been disabled.");
								return true;
							}else{
								pwm.add(p.getName());
								p.sendMessage(tag + ChatColor.BLUE + "Msgwatch for your account has been enabled.");
								return true;
							}
						}else{
							sender.sendMessage(tag + ChatColor.RED + "Only players can use this!");
						}
					}else if(args[0].equalsIgnoreCase("w") || args[0].equalsIgnoreCase("watch")) {
						if(sender instanceof Player){
							Player p = (Player) sender;
							if(args.length < 2){
								if(p.getGameMode().equals(GameMode.SPECTATOR)){
									p.teleport(p.getWorld().getSpawnLocation());
									p.setGameMode(GameMode.ADVENTURE);
									if(p.hasPermission("kaos.owner")){
										p.setPlayerListName(ChatColor.GOLD + p.getName());
									}else if(p.hasPermission("kaos.staff")){
										p.setPlayerListName(ChatColor.BLUE + p.getName());
									}
									p.sendMessage(tag + ChatColor.BLUE + "You are no longer watching.");
								}else{
									p.setGameMode(GameMode.SPECTATOR);
									p.setPlayerListName("");
									p.getWorld().playEffect(p.getLocation(), Effect.MOBSPAWNER_FLAMES, 1);
									p.sendMessage(tag + ChatColor.BLUE + "You are now watching.");
								}
							}else{
								if(Bukkit.getPlayer(args[1]) != null){
									p.setGameMode(GameMode.SPECTATOR);
									p.setPlayerListName("");
									p.teleport(Bukkit.getPlayer(args[1]));
									p.sendMessage(tag + ChatColor.BLUE + "You are now watching.");
								}else{
									p.sendMessage(tag + ChatColor.RED + "Could not find player!");
								}
							}
						}else{
							sender.sendMessage(tag + ChatColor.RED + "Only players can use this!");
						}
					}else if(args[0].equalsIgnoreCase("pli") || args[0].equalsIgnoreCase("playerloginfo")){
						if(sender instanceof Player){
							Player p = (Player) sender;
							if(! pwli.contains(p.getName())){
								pwli.add(p.getName());
								p.sendMessage(tag + ChatColor.BLUE + "You are now watching player logs");
							}else{
								pwli.remove(p.getName());
								p.sendMessage(tag + ChatColor.BLUE + "You are no longer watching player logs");
							}
						}else{
							sender.sendMessage(tag + ChatColor.RED + "Only players can use this!");
						}
					}else{
						sender.sendMessage(tag + ChatColor.BLUE + "Kaos Staffing");
						sender.sendMessage(ChatColor.GRAY + "do " + ChatColor.RED + "/staff help" + ChatColor.GRAY + " for help.");
					}
				}
			}else{
				sender.sendMessage(tag + ChatColor.RED + "You don\'t have permission to do this!");
			}
			return true;
		}
		if(cmd.getName().equalsIgnoreCase("pmc")){
			sender.sendMessage(ChatColor.BLUE + "https://www.planetminecraft.com/server/kaospvp-4020118/");
			return true;
		}
		if(cmd.getName().equalsIgnoreCase("music")){
			if(sender.hasPermission("kaos.owner")){
				if(args.length != 1){
					sender.sendMessage(tag + ChatColor.RED + "use command like:\n" + ChatColor.GOLD + "/music <start/stop/restart/enable/disable>");
				}else{
					switch(args[0]){
						case "start":
							startMusic();
							break;
						case "stop":
							stopMusic();
							break;
						case "restart":
							restartMusic();
							break;
						case "enable":
							musicEnabled = true;
							break;
						case "disable":
							musicEnabled = false;
							break;
						default:
							sender.sendMessage(tag + ChatColor.RED + "use command like:\n" + ChatColor.GOLD + "/music <start/stop/restart>");
							break;
					}
				}
			}else{
				sender.sendMessage(tag + ChatColor.RED + "You don\'t have permission to do this!");
			}
			return true;
		}
		if(cmd.getName().equalsIgnoreCase("discord")){
			sender.sendMessage(ChatColor.BLUE + "https://discord.gg/4q7nwmK");
			return true;
		}
		if(cmd.getName().equalsIgnoreCase("report")){
			if(args.length < 2){
				sender.sendMessage(tag + ChatColor.RED + "Please use command like: /report <player> <reason>");
			}else{
				if(Bukkit.getPlayer(args[0]) != null){
					String reason = "";
					for(int i = 1; i < args.length; i++){
						reason = reason + args[i] + " ";
					}
					for(Player p : Bukkit.getOnlinePlayers()){
						if(p.hasPermission("kaos.staff") || p.hasPermission("*") || p.hasPermission("kaos.owner")){
							p.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System"
									+ ChatColor.DARK_GRAY + "] " + ChatColor.GRAY +
									sender.getName() + " has reported " + args[0] + " for " + reason);
						}
					}
					sender.sendMessage(tag + ChatColor.BLUE + "Your report has been sent!");
				}else{
					sender.sendMessage(tag + ChatColor.RED + "Could not find player");
				}
			}
			return true;
		}
		if(cmd.getName().equalsIgnoreCase("tokens")){
			if(sender instanceof Player){
				Player p = (Player) sender;
				String uuid = p.getUniqueId().toString();
				if(args.length < 1){
					p.sendMessage(tag + ChatColor.GRAY + "========================================");
					p.sendMessage(ChatColor.RED + "/tokens amount " + ChatColor.BLUE + "Show how many tokens a player has");
					p.sendMessage(ChatColor.RED + "/tokens give " + ChatColor.BLUE + "Give your tokens to online players");
					if(sender.hasPermission("kaos.owner")){
					p.sendMessage(ChatColor.RED + "/tokens set " + ChatColor.BLUE + "Set player's tokens count");
					}
					p.sendMessage(tag + ChatColor.GRAY + "========================================");
				}else{
					switch(args[0]){
						case "amount":
							if(args.length < 2){
								p.sendMessage(tag + ChatColor.BLUE + "You have: " + ChatColor.GOLD + getTokens(uuid) + ChatColor.BLUE +
										" tokens");
							}else{
								Player p1 = Bukkit.getPlayer(args[1]);
								if(p1 == null){
									p.sendMessage(tag + ChatColor.RED + "Could not find player! Make sure they are online and you have spelled their name correctly");
								}else{
									String uuid2 = p1.getUniqueId().toString();
									p.sendMessage(tag + ChatColor.BLUE + args[1] + " has " + ChatColor.GOLD + getTokens(uuid2) +
											ChatColor.BLUE + " tokens");
								}
							}
							break;
						case "give":
							if(args.length < 3){
								p.sendMessage(tag + ChatColor.RED + "Use command like:\n/tokens give <player> <amount>");
							}else{
								Player p1 = Bukkit.getPlayer(args[1]);
								if(p1 == null){
									p.sendMessage(tag + ChatColor.RED + "Could not find player! Make sure they are online and you have spelled their name correctly");
								}else{
									String uuid2 = p1.getUniqueId().toString();
									if(! StringUtils.isNumeric(args[2])){
										p.sendMessage(tag + ChatColor.RED + "Invalid number");
										return true;
									}
									Long amount = Long.parseLong(args[2]);
									if(amount < 0)return true;
									if( ( getTokens(uuid)-amount) >= 0){
										setTokens(uuid, getTokens(uuid)-amount);
										setTokens(uuid2, getTokens(uuid2)+amount);
										p.sendMessage(tag + ChatColor.BLUE + "You have transfered " + ChatColor.GOLD +
												amount + ChatColor.BLUE + " tokens to " + args[1]);
										p1.sendMessage(tag + ChatColor.BLUE + "You have received " + ChatColor.GOLD +
												amount + ChatColor.BLUE + " tokens from " + p.getName());
									}else{
										p.sendMessage(tag + ChatColor.RED + "You don\'t have enough tokens!");
									}
								}
							}
							break;
						case "set":
							if(p.hasPermission("kaos.owner")){
								if(args.length < 3){
									p.sendMessage(tag + ChatColor.RED + "Use command like:\n/tokens set <player> <amount>");
								}else{
									Player p1 = Bukkit.getPlayer(args[1]);
									if(p1 == null){
										p.sendMessage(tag + ChatColor.RED + "Could not find player! Make sure they are online and you have spelled their name correctly");
									}else{
										String uuid2 = p1.getUniqueId().toString();
										if(! StringUtils.isNumeric(args[2])){
											p.sendMessage(tag + ChatColor.RED + "Invalid number");
											return true;
										}
										setTokens(uuid2, Long.parseLong(args[2]));
										p.sendMessage(tag + ChatColor.BLUE + "The tokens have been set for specified player");
									}
								}
							}else{
								p.sendMessage(tag + ChatColor.RED + "You cannot do this!");
							}
							break;
						default:
							p.sendMessage(tag + ChatColor.GRAY + "========================================");
							p.sendMessage(ChatColor.RED + "/tokens amount " + ChatColor.BLUE + "Show how many tokens a player has");
							p.sendMessage(ChatColor.RED + "/tokens give " + ChatColor.BLUE + "Give your tokens to online players");
							if(sender.hasPermission("kaos.owner")){
							p.sendMessage(ChatColor.RED + "/tokens set " + ChatColor.BLUE + "Set player's tokens count");
							}
							p.sendMessage(tag + ChatColor.GRAY + "========================================");
							break;
					}
				}
			}else{
				sender.sendMessage(tag + ChatColor.RED + "Only players can use this!");
			}
			return true;
		}
		if(cmd.getName().equalsIgnoreCase("shop")){
			if(sender instanceof Player){
				Player p = (Player) sender;
				p.openInventory(shopInvent());
			}else{
				sender.sendMessage(tag + ChatColor.RED + "Only players can use this!");
			}
			return true;
		}
		if(cmd.getName().equalsIgnoreCase("welcome")){
			if(sender instanceof Player){
				if(sender.hasPermission("kaos.owner")){
					Player p = (Player) sender;
					if(args.length != 1){
						p.sendMessage(tag + ChatColor.RED + "Use command like: /welcome <player>");
					}else{
						String pname = args[0];
						p.chat("Welcome " + pname + " to KaosPvP! I hope you enjoy your stay!");
						p.chat("Make sure to read the /rules and /help to begin!");
					}
				}else{
					sender.sendMessage(tag + ChatColor.RED + "You cannot do this!");
				}
			}else{
				sender.sendMessage(tag + ChatColor.RED + "Only players can use this!");
			}
			return true;
		}
		if(cmd.getName().equalsIgnoreCase("broadcast")){
			if(sender.hasPermission("kaos.owner")){
				if(args.length < 1){ // 0
					sender.sendMessage(tag + ChatColor.RED + "Use like: /broadcast <message>");
				}else{
					String msg = "";
					for(int i = 0; i < args.length; i++){
						msg = msg + args[i] + " ";
					}
					msg = ChatColor.translateAlternateColorCodes('&', msg);
					Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', 
							"&4>&c>&7> &l") + msg);
				}
			}else{
				sender.sendMessage(tag + ChatColor.RED + "You cannot do this!");
			}
			return true;
		}
		if(cmd.getName().equalsIgnoreCase("emeralds")){
			if(sender instanceof Player){
				Player p = (Player) sender;
				String uuid = p.getUniqueId().toString();
				p.sendMessage(tag + ChatColor.BLUE + "You have " + ChatColor.GOLD + getEmeralds(uuid) + ChatColor.BLUE + " emeralds");
			}else{
				sender.sendMessage(tag + ChatColor.RED + "Only players can use this!");
			}
			return true;
		}
		return false;
	}
	
////////////// Messaging system stuff aswell //////////////
	private void pstp(Player p){
		p.playNote(p.getLocation(), Instrument.PIANO, Note.sharp(1, Tone.F));
	}
	private boolean isPOnline(String name){
		for(Player p : Bukkit.getServer().getOnlinePlayers()){
			if(p.getName().equals(name)) return true;
		}
		return false;
	}
	public void setPlayerReplyName(String p1, String p2){
		for(int i = 0; i < prt.size(); i++){
			String s1 = prt.get(i);
			String s2[] = s1.split(":");
			if(s2[0].equals(p1)){
				String s3 = p1 + ":" + p2;
				prt.set(i, s3);
				return;
			}
		}
		String s4 = p1 + ":" + p2;
		prt.add(s4);
		return;
	}
	
	public String getReplyName(String p1){
		for(int i = 0; i < prt.size(); i++){
			String s1[] = prt.get(i).split(":");
			if(s1[0].equals(p1)){
				return s1[1];
			}
		}
		return null;
	}
	
	@EventHandler
	public void onQuit(PlayerQuitEvent e){
		if( pwm.contains(e.getPlayer().getName()) ){
			pwm.remove(e.getPlayer().getName());
		}
		if( pwli.contains(e.getPlayer().getName())){
			pwli.remove(e.getPlayer().getName());
		}
	}
////////////// End of messaging system stuff aswell //////////////
	
	// Join and Leave messages
	@EventHandler(priority=EventPriority.LOWEST)
	public void onJoinM(PlayerJoinEvent e){
		if(! e.getPlayer().hasPlayedBefore()){
			e.setJoinMessage(tag + ChatColor.DARK_GREEN + "Welcome our new player " + e.getPlayer().getName());
		}else{
			if(isSjm(e.getPlayer().getUniqueId().toString())){
				e.setJoinMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GREEN + "+ " + e.getPlayer().getName() + ChatColor.DARK_GRAY + "]");
			}else{
				e.setJoinMessage("");
			}
		}
		for(String name : pwli){
			Bukkit.getPlayer(name).sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System" + ChatColor.DARK_GRAY + "] " +
					ChatColor.GRAY + e.getPlayer().getName() + " has joined");
		}
	}
	@EventHandler(priority=EventPriority.LOWEST)
	public void onQuitM(PlayerQuitEvent e){
		if(isSjm(e.getPlayer().getUniqueId().toString())){
			e.setQuitMessage(ChatColor.DARK_GRAY + "[" + ChatColor.RED + "- " + e.getPlayer().getName() + ChatColor.DARK_GRAY + "]");
		}else{
			e.setQuitMessage("");
		}
		for(String name : pwli){
			Bukkit.getPlayer(name).sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "@System" + ChatColor.DARK_GRAY + "] " +
					ChatColor.GRAY + e.getPlayer().getName() + " has left");
		}
	}
	
	// Deal with punishments boi
	@EventHandler(priority=EventPriority.HIGHEST)
	public void setupFilesOnJoin(PlayerLoginEvent e){
		String uuid = e.getPlayer().getUniqueId().toString();
		String folLoc = this.getDataFolder().getPath() + File.separator + uuid + File.separator;
		File bans = new File(folLoc + "bans.kaes");
		File mutes = new File(folLoc + "mutes.kaes");
		File jails = new File(folLoc + "jails.kaes");
		File tokens = new File(folLoc + "tokens.kaes");
		File ljm = new File(folLoc + "ljm.kaes");
		File emeralds = new File(folLoc + "emeralds.kaes");
		try{
			if(! new File(folLoc).exists()){
				new File(folLoc).mkdirs();
			}
			if(! bans.exists()){
				bans.createNewFile();
				Punished.setBanned(uuid, 0, null);
			}
			if(! mutes.exists()){
				mutes.createNewFile();
				Punished.setMuted(uuid, 0, null);
			}
			if(! jails.exists()){
				jails.createNewFile();
				Punished.setJailed(uuid, 0, null);
			}
			if(! tokens.exists()){
				tokens.createNewFile();
				setTokens(uuid, 0L);
			}
			if(! ljm.exists()){
				ljm.createNewFile();
				setSjm(uuid, false);
			}
			if(! emeralds.exists()){
				emeralds.createNewFile();
				setEmeralds(uuid,0);
			}
		}catch (IOException ex){
			ex.printStackTrace();
		}
		getLogger().info("Login event triggered!");
		String pu = e.getPlayer().getUniqueId().toString(); // player uuid
		getLogger().info("UUID: " + pu);
		////////// check if player is banned ////////////
		Punished pb = Punished.isBanned(pu); // player banned?
		if(pb.punished){
			getLogger().info("Player is banned!");
			e.disallow(Result.KICK_BANNED, tag + ChatColor.RED + ChatColor.BOLD + "Banned from server!\n"
					+ ChatColor.RED + "Reason: " + ChatColor.AQUA + pb.reason + ChatColor.RED + ".\n"
					+ ChatColor.RED + "Expiry: " + ChatColor.AQUA + Long.toString((long)((long)pb.expirySecs/60/60/24))
					+ ChatColor.RED + " days");
		}
	}
	@EventHandler
	public void stopMuted(AsyncPlayerChatEvent e){
		String pu = e.getPlayer().getUniqueId().toString();
		Punished pm = Punished.isMuted(pu);
		if(pm.punished){
			e.setCancelled(true);
			e.getPlayer().sendMessage(ChatColor.RED + "You are muted for another " + ChatColor.DARK_RED + (long)(pm.expirySecs/60)
			+ ChatColor.RED + " minutes, " + ChatColor.DARK_RED + pm.expirySecs%60 + ChatColor.RED + " seconds.");
		}
	}
	@EventHandler
	public void stopMutedMsg(PlayerCommandPreprocessEvent e){
		String pu = e.getPlayer().getUniqueId().toString();
		Punished pm = Punished.isMuted(pu);
		if(e.getMessage().toLowerCase().startsWith("/msg") || e.getMessage().toLowerCase().startsWith("/r ") ||
				e.getMessage().toLowerCase().startsWith("/report") ){
			if(pm.punished){
				e.setCancelled(true);
				e.getPlayer().sendMessage(ChatColor.RED + "You are muted for another " + ChatColor.DARK_RED +
				Long.toString((long)(pm.expirySecs/60)) + ChatColor.RED + " minutes, " + ChatColor.DARK_RED +
				pm.expirySecs%60 + ChatColor.RED + " seconds.");
			}
		}
	}
	@EventHandler
	public void stopJailedCmd(PlayerCommandPreprocessEvent e){
		String pu = e.getPlayer().getUniqueId().toString();
		Punished pj = Punished.isJailed(pu);
		if(pj.punished){
			e.setCancelled(true);
			e.getPlayer().sendMessage(ChatColor.RED + "You are jailed! You cannot do this!");
		}
	}
	@EventHandler
	public void stopJailed(AsyncPlayerChatEvent e){
		String pu = e.getPlayer().getUniqueId().toString();
		Punished pj = Punished.isJailed(pu);
		if(pj.punished){
			e.setCancelled(true);
			e.getPlayer().sendMessage(ChatColor.RED + "You are jailed! You cannot do this!");
		}
	}
	final int HOUR = 60*60;
	final int MINUTE = 60;
	@EventHandler
	public void jailDoorExit(PlayerInteractEvent e){
		jailLoc = new Location(Bukkit.getWorld("kaospvp"), 1106, 32, -236);
		jailLeaveLoc = new Location(Bukkit.getWorld("kaospvp"), 1103, 33, -238);
		Punished pj = Punished.isJailed(e.getPlayer().getUniqueId().toString());
		if(e.getClickedBlock() == null) return;
		Location cbl = e.getClickedBlock().getLocation(); // clicked block location
		boolean ird =  // is right door?
				cbl.getBlockX() == jailLeaveLoc.getBlockX() &&
				cbl.getBlockY() == jailLeaveLoc.getBlockY() &&
				cbl.getBlockZ() == jailLeaveLoc.getBlockZ();
		if(ird){
			if(pj.punished){
				e.getPlayer().sendMessage(
						tag + ChatColor.GRAY + "You still have " +
						ChatColor.RED + pj.expirySecs / (60*60*24) + ChatColor.GRAY + " days, " +
						ChatColor.RED + ((pj.expirySecs/HOUR)%24) + ChatColor.GRAY + " hours, " +
						ChatColor.RED + ((pj.expirySecs/MINUTE) % 60) + ChatColor.GRAY + " minutes!");
			}else{
				e.getPlayer().teleport(e.getPlayer().getWorld().getSpawnLocation());
				e.getPlayer().sendMessage(tag + ChatColor.GREEN + "You are free from jail!");
			}
		}
	}

	//////// custom format stuff ////////////
	@EventHandler
	public void chatStuff(AsyncPlayerChatEvent e){
		String uuid = e.getPlayer().getUniqueId().toString();
		//String name = e.getPlayer().getName();
		// -- stuff
		e.setMessage(e.getMessage().replaceAll("--tokens", ChatColor.translateAlternateColorCodes('&',
				"&6[&9" + Long.toString(getTokens(uuid)) + " Tokens&6]&r")));
		e.setMessage(e.getMessage().replaceAll("--emeralds", ChatColor.translateAlternateColorCodes('&',
				"&6[&9" + Long.toString(getEmeralds(uuid)) + " Emeralds&6]&r")));
		//e.setMessage(e.getMessage().replaceAll("--kills", ChatColor.translateAlternateColorCodes('&',
		//		"&6[&9" + Integer.toString(e.getPlayer().getStatistic(Statistic.PLAYER_KILLS)) + " Kills&6]&r")));
		//e.setMessage(e.getMessage().replaceAll("--deaths", ChatColor.translateAlternateColorCodes('&',
		//		"&6[&9" + Integer.toString(e.getPlayer().getStatistic(Statistic.DEATHS)) + " Deaths&6]&r")));
		// emojis
		e.setMessage(e.getMessage().replace("<3", ChatColor.translateAlternateColorCodes('&', "&c❤&r")));
		e.setMessage(e.getMessage().replace("@@", "●"));
		e.setMessage(e.getMessage().replace("/!\\", "⚠"));
		e.setMessage(e.getMessage().replace("->", "➜"));
		e.setMessage(e.getMessage().replace(">>", "➤"));
		e.setMessage(e.getMessage().replace("<>", "✰"));
		e.setMessage(e.getMessage().replace("XX", "✖"));
		e.setMessage(e.getMessage().replace("{}", "✿"));
		e.setMessage(e.getMessage().replace("[m]", "✉"));
		e.setMessage(e.getMessage().replace(",/", "✔"));
		/////// other chat stuff
		while(e.getMessage().contains("hhhhhhhhh")){
			e.setMessage(e.getMessage().replace("hhhhhhhhh", "hhhh"));
		}
		if(e.getPlayer().hasPermission("kaos.cchat") || e.getPlayer().hasPermission("kaos.owner"))
			e.setMessage(ChatColor.translateAlternateColorCodes('&', e.getMessage()));
		if(e.getPlayer().hasPermission("kaos.owner")){
			if(! e.getPlayer().getGameMode().equals(GameMode.SPECTATOR))
				e.getPlayer().setPlayerListName(ChatColor.GOLD + e.getPlayer().getName());
			e.getPlayer().setDisplayName(
					ChatColor.translateAlternateColorCodes('&', "&r[&6Owner&r]&6" + e.getPlayer().getName() + "&r"));
		}else if(e.getPlayer().hasPermission("kaos.staff")){
			if(! e.getPlayer().getGameMode().equals(GameMode.SPECTATOR))
				e.getPlayer().setPlayerListName(ChatColor.BLUE + e.getPlayer().getName());
			e.getPlayer().setDisplayName(
					ChatColor.translateAlternateColorCodes('&', "&r[&9Staff&r]&9" + e.getPlayer().getName() + "&r"));
		}else{
			e.getPlayer().setPlayerListName(ChatColor.GRAY + e.getPlayer().getName());
			e.getPlayer().setDisplayName(
					ChatColor.translateAlternateColorCodes('&', "&r[&7Default&r]&7" + e.getPlayer().getName() + "&r"));
		}
		e.setFormat(e.getPlayer().getDisplayName() + " >> " + e.getMessage().replaceAll("%", ""));
	}
	
/////////////// Stops blacklisted commands ///////////////
	private final String blCmds[] = {
			"/pl", "/?", "/minecraft:tell", "/bukkit:", "/me",
			"/ver", "/about", "/icanhasbukkit", "/minecraft:", "//"
			};
	
	@EventHandler
	public void onCmdSend(PlayerCommandPreprocessEvent e){
		if(! e.getPlayer().hasPermission("*")){
			for(String cmd : blCmds){
				if(e.getMessage().toLowerCase().startsWith(cmd.toLowerCase())){
					e.getPlayer().sendMessage(tag + ChatColor.RED + "You cannot do this!");
					e.setCancelled(true);
					return;
				}
			}
		}
	}
	
/////////////// End of Stops blacklisted commands ///////////////
	
	// clear stupid and useless items
	public void clearJunk(){
		World world = Bukkit.getWorld("kaospvp");
		List<Entity> list = world.getEntities();
		for(Entity e : list){
			if(e instanceof Item){
				Item it = (Item) e;
				if( it.getItemStack().getType() == Material.POTION &&
					it.getItemStack().getDurability() == 16453){
					e.remove();
				}
				if( it.getItemStack().getType() == Material.GOLDEN_APPLE &&
					it.getItemStack().getDurability() == 0){
					e.remove();
				}
				if( it.getItemStack().getType() == Material.ARROW){
					e.remove();
				}
				if( it.getItemStack().getType() == Material.GLASS_BOTTLE){
					e.remove();
				}
				if( it.getItemStack().getType() == Material.DIAMOND_BOOTS &&
					it.getItemStack().getEnchantments().size() == 0){
					e.remove();
				}
				if( it.getItemStack().getType() == Material.DIAMOND_LEGGINGS &&
					it.getItemStack().getEnchantments().size() == 0){
					e.remove();
				}
				if( it.getItemStack().getType() == Material.DIAMOND_CHESTPLATE &&
					it.getItemStack().getEnchantments().size() == 0){
					e.remove();
				}
				if( it.getItemStack().getType() == Material.DIAMOND_HELMET &&
					it.getItemStack().getEnchantments().size() == 0){
					e.remove();
				}
				if( it.getItemStack().getType() == Material.DIAMOND_SWORD &&
					it.getItemStack().getEnchantments().size() == 0){
					e.remove();	
				}
				if( it.getItemStack().getType() == Material.BOW &&
					it.getItemStack().getEnchantments().size() == 0){
					e.remove();	
				}
				if( it.getItemStack().getType() == Material.WOOD_AXE ||
					it.getItemStack().getType() == Material.STONE_AXE ||
					it.getItemStack().getType() == Material.GOLD_AXE ||
					it.getItemStack().getType() == Material.IRON_AXE ||
					it.getItemStack().getType() == Material.DIAMOND_AXE){
					e.remove();
				}
			}
		}
	}
	// end of clearing stupid and useless junk
	@EventHandler(priority=EventPriority.LOWEST)
	public void otherJoinEventStuff(PlayerJoinEvent e){
		Player p = e.getPlayer();
		p.sendMessage(tag + ChatColor.GRAY + "=================================");
		p.sendMessage(tag + ChatColor.BLUE + "Welcome to kaospvp!");
		p.sendMessage(tag + ChatColor.BLUE + "Do " + ChatColor.RED + "/help" + ChatColor.BLUE + " to get started");
		p.sendMessage(tag + ChatColor.BLUE + "And make sure to read the " + ChatColor.RED + "/rules");
		p.sendMessage(tag + ChatColor.GRAY + "=================================");
	}
	@EventHandler
	public void helpMessage(PlayerCommandPreprocessEvent e){
		if(e.getMessage().startsWith("/help")){
			e.setCancelled(true);
			Player p = e.getPlayer();
			p.sendMessage(tag + ChatColor.GRAY + "=================================");
			p.sendMessage(ChatColor.BLUE + "KaosPvP is a custom massive pvp like server");
			p.sendMessage(ChatColor.BLUE + " with chaotic enchantments, pots and gaps.");
			p.sendMessage(ChatColor.BLUE + "Grab an axe and some gear, then step into pvp");
			p.sendMessage(ChatColor.BLUE + " for an awesome and unique pvp experience.");
			p.sendMessage(ChatColor.AQUA + "---Commands---");
			p.sendMessage(ChatColor.RED + "/help " + ChatColor.BLUE + "This help message");
			p.sendMessage(ChatColor.RED + "/rules " + ChatColor.BLUE + "Server rules");
			p.sendMessage(ChatColor.RED + "/report " + ChatColor.BLUE + "Report a player to the online staff");
			p.sendMessage(ChatColor.RED + "/trash " + ChatColor.BLUE + "Throw away useless items");
			p.sendMessage(ChatColor.RED + "/msg " + ChatColor.BLUE + "Send a private message");
			p.sendMessage(ChatColor.RED + "/r " + ChatColor.BLUE + "Reply to your last private message");
			p.sendMessage(ChatColor.RED + "/discord " + ChatColor.BLUE + "Display discord link");
			p.sendMessage(ChatColor.RED + "/pmc " + ChatColor.BLUE + "Display PMC link");
			p.sendMessage(ChatColor.RED + "/tokens " + ChatColor.BLUE + "Everything to do with tokens");
			p.sendMessage(ChatColor.RED + "/shop " + ChatColor.BLUE + "Open the shop");
			p.sendMessage(tag + ChatColor.GRAY + "=================================");
		}
	}
	
	List<String> uuidsClickItem = new ArrayList<String>();
	List<Long> lastClickItem = new ArrayList<Long>();
	@EventHandler(priority=EventPriority.HIGHEST)
	public void onClickFrame(PlayerInteractEntityEvent e){
		if(!(e.getRightClicked() instanceof ItemFrame)) return;
		String uuid = e.getPlayer().getUniqueId().toString();
		long curTime = System.currentTimeMillis();
		int posInList;
		if(uuidsClickItem.contains(uuid)){
			posInList = uuidsClickItem.indexOf(uuid);
			if(curTime < (lastClickItem.get(posInList) + 200)){
				e.getPlayer().sendMessage(tag + ChatColor.RED + "Please slow down clicking item frames!");
				Vector movDirection = e.getPlayer().getEyeLocation().getDirection();
				movDirection = movDirection.normalize().multiply(-2);
				e.getPlayer().setVelocity(movDirection);
				e.setCancelled(true);
			}
			if(curTime < (lastClickItem.get(posInList) + 50)){
				e.getPlayer().kickPlayer(tag + ChatColor.RED + "Please do not spam item frames!");
				
			}
			lastClickItem.set(posInList, curTime);
		}else{
			uuidsClickItem.add(uuid);
			lastClickItem.add(curTime);
		}
	}
	// FIXME Fix this!
	/*List<String> uuidsClick = new ArrayList<String>();
	List<Long> lastClick = new ArrayList<Long>();
	@EventHandler(priority=EventPriority.HIGHEST)
	public void onRightClick(PlayerInteractEvent e){
		if(e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
			String uuid = e.getPlayer().getUniqueId().toString();
			long curTime = System.currentTimeMillis();
			int posInList;
			if(uuidsClick.contains(uuid)){
				posInList = uuidsClick.indexOf(uuid)-1;
				if(curTime < (lastClick.get(posInList) + 50)){
					e.setCancelled(true);
				}
				lastClickItem.set(posInList, curTime);
			}else{
				uuidsClick.add(uuid);
				lastClick.add(curTime);
			}
		}
	}*/
	
	public void setTokens(String uuid, long amount){
		String folLoc = this.getDataFolder().getPath() + File.separator + uuid + File.separator;
		File f = new File(folLoc + "tokens.kaes");
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(f));
			bw.write(Long.toString(amount));
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			try{
				bw.close();
			}catch(IOException ex){
				ex.printStackTrace();
			}
		}
	}
	public long getTokens(String uuid){
		String folLoc = this.getDataFolder().getPath() + File.separator + uuid + File.separator;
		File f = new File(folLoc + "tokens.kaes");
		long amount = 0;
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(f));
			amount = Long.parseLong(br.readLine());
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			try{
				br.close();
			}catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return amount;
	}
	public void setEmeralds(String uuid, long amount){
		String folLoc = this.getDataFolder().getPath() + File.separator + uuid + File.separator;
		File f = new File(folLoc + "emeralds.kaes");
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(f));
			bw.write(Long.toString(amount));
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			try{
				bw.close();
			}catch(IOException ex){
				ex.printStackTrace();
			}
		}
	}
	public long getEmeralds(String uuid){
		String folLoc = this.getDataFolder().getPath() + File.separator + uuid + File.separator;
		File f = new File(folLoc + "emeralds.kaes");
		long amount = 0;
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(f));
			amount = Long.parseLong(br.readLine());
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			try{
				br.close();
			}catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return amount;
	}
	boolean isSjm(String uuid){
		String folLoc = this.getDataFolder().getPath() + File.separator + uuid + File.separator;
		File f = new File(folLoc + "ljm.kaes");
		boolean isit = false;
		BufferedReader br = null;
		try{
			br = new BufferedReader(new FileReader(f));
			isit = Boolean.parseBoolean(br.readLine());
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			try{
				br.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
		return isit;
	}
	void setSjm(String uuid, boolean val){
		String folLoc = this.getDataFolder().getPath() + File.separator + uuid + File.separator;
		File f = new File(folLoc + "ljm.kaes");
		BufferedWriter bw = null;
		try{
			bw = new BufferedWriter(new FileWriter(f));
			bw.write(Boolean.toString(val));
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			try{
				bw.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	@EventHandler
	public void getEmerald(PlayerPickupItemEvent e){
		Player p = e.getPlayer();
		String uuid = p.getUniqueId().toString();
		if(e.getItem().getItemStack().getType().equals(Material.EMERALD)){
			e.setCancelled(true);
			int amount = e.getItem().getItemStack().getAmount();
			e.getItem().remove();
			setEmeralds(uuid, getEmeralds(uuid)+amount);
			p.playNote(p.getLocation(), Instrument.PIANO, Note.natural(1, Tone.A));
		}
	}
	@EventHandler(priority=EventPriority.HIGHEST)
	public void customDeath(EntityDamageByEntityEvent e){
		if(e.isCancelled())return;
		if(e.getEntity() instanceof Player && e.getDamager() instanceof Player){
			Player p = (Player) e.getEntity();
			if(e.getFinalDamage() >= p.getHealth()){
				Player killer = (Player) e.getDamager();
				String uuid2 = killer.getUniqueId().toString();
				e.setCancelled(true);
				if(! p.getName().equals(killer.getName())){ // if they were killed by someone else, not themselves
					setTokens(uuid2, getTokens(uuid2)+2);
					killer.sendMessage(tag + ChatColor.BLUE + "You have received " + ChatColor.GOLD + "2" +
							ChatColor.BLUE + " tokens for killing " + p.getName());
				}
				Bukkit.getServer().broadcastMessage(ChatColor.GRAY + killer.getName() + " destroyed " + p.getName());
				// Set statistics
				//killer.setStatistic(Statistic.KILL_ENTITY, killer.getStatistic(Statistic.KILL_ENTITY) + 1);
				//p.setStatistic(Statistic.DEATHS, p.getStatistic(Statistic.DEATHS) + 1);
				// Reset health, so they dont die
				p.setHealth(p.getMaxHealth());
				// Inventory clearing
				p.getInventory().clear();
				ItemStack air = new ItemStack(Material.AIR);
				p.getInventory().setHelmet(air);
				p.getInventory().setChestplate(air);
				p.getInventory().setLeggings(air);
				p.getInventory().setBoots(air);
				// Drop emerald at death location
				ItemStack reward = new ItemStack(Material.EMERALD);
				p.getWorld().dropItemNaturally(p.getLocation(), reward);
				// Clear potion effects
				for(PotionEffect pe : p.getActivePotionEffects()){
					p.removePotionEffect(pe.getType());
				}
				// Stop infinite kill glitch
				p.setGameMode(GameMode.SPECTATOR);
				p.setGameMode(GameMode.ADVENTURE);
				// Send them to the SPAWN of the world
				p.teleport(p.getWorld().getSpawnLocation());
				p.setFireTicks(0);
			}
		}
	}
	@EventHandler(priority=EventPriority.LOWEST)
	public void customDeathNonPlayerFallback(EntityDamageEvent e){
		if(e.getCause().equals(DamageCause.FALL)) return;
		if(e.getEntity() instanceof Player){
			Player p = (Player) e.getEntity();
			if(e.getCause().equals(DamageCause.ENTITY_ATTACK)){
				// no need to do anything here, this part is controlled in the customDeath method
			}else{
				if(e.getFinalDamage() >= p.getHealth()){
					e.setCancelled(true);
					Bukkit.getServer().broadcastMessage(ChatColor.GRAY + p.getName() + " died");
					// Set statistics
					//p.setStatistic(Statistic.DEATHS, p.getStatistic(Statistic.DEATHS) + 1);
					// Reset health, so they dont die
					p.setHealth(p.getMaxHealth());
					// Inventory clearing
					p.getInventory().clear();
					ItemStack air = new ItemStack(Material.AIR);
					p.getInventory().setHelmet(air);
					p.getInventory().setChestplate(air);
					p.getInventory().setLeggings(air);
					p.getInventory().setBoots(air);
					// Clear potion effects
					for(PotionEffect pe : p.getActivePotionEffects()){
						p.removePotionEffect(pe.getType());
					}
					// Stop infinite kill glitch
					p.setGameMode(GameMode.SPECTATOR);
					p.setGameMode(GameMode.ADVENTURE);
					// send them to the SPAWN of the world
					p.teleport(p.getWorld().getSpawnLocation());
					p.setFireTicks(0);
				}
			}
		}
	}
	@EventHandler
	public void customDeathNonPlayerFallbackFailedFallback(PlayerDeathEvent e){
		e.setDeathMessage(ChatColor.GRAY + e.getEntity().getName() + " died");
		getLogger().info(ChatColor.RED + "Wtf was that");
	}
	@SuppressWarnings("deprecation")
	@EventHandler
	public void anvilStuff(PlayerInteractEvent e){
		if(e.getClickedBlock() == null)return;
		if(e.getClickedBlock().getType().equals(Material.ANVIL)){
			e.setCancelled(true);
			Player p = e.getPlayer();
			String uuid = p.getUniqueId().toString();
			long tokens = getTokens(uuid);
			if(p.getItemInHand().getType() == Material.AIR ||
					p.getItemInHand().getType() == Material.GOLDEN_APPLE ||
					p.getItemInHand().getType() == Material.ARROW ||
					p.getItemInHand().getType() == Material.POTION){
				
				p.sendMessage(tag + ChatColor.RED + "You can\'t repair that!");
			}else{
				if(tokens < 1){
					p.sendMessage(tag + ChatColor.RED + "You need at least 1 token to repair things!!");
				}else{
					if(p.getItemInHand().getDurability() > 0){
						p.getItemInHand().setDurability((short) 0);
						setTokens(uuid, getTokens(uuid)-1);
						p.sendMessage(tag + ChatColor.BLUE + "Your item has been repaired");
					}else{
						p.sendMessage(tag + ChatColor.RED + "This item isn\'t broken");
					}
				}
			}
		}
	}
	// Anti fall-damage
	@EventHandler
	public void stopFall(EntityDamageEvent e){
		if(e.getCause().equals(DamageCause.FALL)) e.setCancelled(true);
	}
	// Stop people from crafting stuff
	@EventHandler
	public void stopCraft(PrepareItemCraftEvent e){
		for(HumanEntity he : e.getViewers()){
			if(he instanceof Player){
				Player p = (Player) he;
				if(! p.hasPermission("kaos.owner")) e.getInventory().setResult(new ItemStack(Material.AIR));
			}
		}
	}
	// Stop the hunger
	@EventHandler
	public void noHunger(FoodLevelChangeEvent e){
		e.setCancelled(true);
		e.setFoodLevel(20);
	}
	// token shop stuff
	private final String shopName = "KaosPvP Shop";
	private ItemStack getItemSpacer(){
		return new ItemStack(Material.STAINED_GLASS_PANE,64,(short)15);
	}
	public Inventory shopInvent(){
		Inventory inv = Bukkit.createInventory(null, 36, shopName);
		
		ItemStack str = new ItemStack(Material.POTION, 1, (short) 8201);
		ItemMeta strM = str.getItemMeta();
		List<String> strL = new ArrayList<String>();
		strM.setDisplayName(ChatColor.RED + "Strength");
		strL.add(ChatColor.GOLD + "120 Tokens");
		strM.setLore(strL);
		str.setItemMeta(strM);
		inv.addItem(str);
		
		ItemStack gaps = new ItemStack(Material.GOLDEN_APPLE, 2, (short) 1);
		ItemMeta gapsM = gaps.getItemMeta();
		List<String> gapsL = new ArrayList<String>();
		gapsM.setDisplayName(ChatColor.RED + "Golden Apple");
		gapsL.add(ChatColor.GOLD + "10 Tokens");
		gapsM.setLore(gapsL);
		gaps.setItemMeta(gapsM);
		inv.addItem(gaps);
		
		for(int i = 0; i < 6; i++){
			inv.addItem(getItemSpacer());
		}
		
		ItemStack ljm = new ItemStack(Material.DAYLIGHT_DETECTOR);
		ItemMeta ljmM = ljm.getItemMeta();
		List<String> ljmL = new ArrayList<String>();
		ljmM.setDisplayName(ChatColor.RED + "Leave/Join Messages");
		ljmL.add(ChatColor.GOLD + "400 Tokens");
		ljmM.setLore(ljmL);
		ljm.setItemMeta(ljmM);
		inv.addItem(ljm);
		
		ItemStack exp = new ItemStack(Material.EXP_BOTTLE,20);
		ItemMeta expM = exp.getItemMeta();
		List<String> expL = new ArrayList<String>();
		expM.setDisplayName(ChatColor.RED + "Experience Bottles");
		expL.add(ChatColor.GOLD + "1 Token");
		expM.setLore(expL);
		exp.setItemMeta(expM);
		inv.addItem(exp);
		
		// remove the item spacers
		inv.remove(Material.STAINED_GLASS_PANE);
		
		return inv;
	}
	
	@EventHandler
	public void shopClick(InventoryClickEvent e){
		if(e.getInventory().getName().equals(shopName) && e.getRawSlot() > 36){
			e.setCancelled(true);
			return;
		}
		if(e.getClickedInventory() == null){
			e.setCancelled(true);
			return;
		}
		if(e.getClickedInventory().getName() == null){
			e.setCancelled(true);
			return;
		}
		if(e.getClickedInventory().getName().equals(shopName)){
			Player p = (Player) e.getWhoClicked();
			String uuid = p.getUniqueId().toString();
			long tokens = getTokens(uuid);
			e.setCancelled(true);
			if(! e.getCurrentItem().hasItemMeta()) return;
			String name = e.getCurrentItem().getItemMeta().getDisplayName();
			if(name.equals(ChatColor.RED + "Strength")){
				if(tokens < 120){
					p.sendMessage(tag + ChatColor.RED + "You don\'t have enough tokens!");
					p.closeInventory();
				}else{
					ItemStack str = new ItemStack(Material.POTION, 1, (short) 8201);
					p.getInventory().addItem(str);
					setTokens(uuid, getTokens(uuid) - 120);
					p.sendMessage(tag + ChatColor.BLUE + "Your purchase was a success");
				}
			}
			if(name.equals(ChatColor.RED + "Golden Apple")){
				if(tokens < 10){
					p.sendMessage(tag + ChatColor.RED + "You don\'t have enough tokens!");
					p.closeInventory();
				}else{
					ItemStack gaps = new ItemStack(Material.GOLDEN_APPLE, 2, (short) 1);
					p.getInventory().addItem(gaps);
					setTokens(uuid, getTokens(uuid) - 10);
					p.sendMessage(tag + ChatColor.BLUE + "Your purchase was a success");
				}
			}
			if(name.equals(ChatColor.RED + "Leave/Join Messages")){
				if(tokens < 400){
					p.sendMessage(tag + ChatColor.RED + "You don\'t have enough tokens!");
					p.closeInventory();
				}else{
					if(isSjm(uuid)){
						p.sendMessage(tag + ChatColor.RED + "You already have this!");
						p.closeInventory();
					}else{
						setSjm(uuid, true);
						setTokens(uuid, getTokens(uuid) - 400);
						p.sendMessage(tag + ChatColor.BLUE + "Your purchase was a success");
					}
				}
			}
			if(name.equals(ChatColor.RED + "Experience Bottles")){
				if(tokens < 1){
					p.sendMessage(tag + ChatColor.RED + "You don\'t have enough tokens!");
					p.closeInventory();
				}else{
					ItemStack exp = new ItemStack(Material.EXP_BOTTLE,20);
					p.getInventory().addItem(exp);
					setTokens(uuid, getTokens(uuid) - 1);
					p.sendMessage(tag + ChatColor.BLUE + "Your purchase was a success");
				}
			}
		}
	}
	
}