package com.namelessmc.plugin.NamelessSpigot.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.UUID;

import org.bukkit.entity.Player;

/**
 * Helper-class for getting UUIDs of players
 */
public class UUIDFetcher {
	
	/**
	 * @param player The player
	 * @return The UUID of the given player
	 */
	public static UUID getUUID(Player player) {
		return getUUID(player.getName());
	}
	
	/**
	 * @param playername The name of the player
	 * @return The UUID of the given player
	 */
	public static UUID getUUID(String playername) {
		String output = callURL("https://api.mojang.com/users/profiles/minecraft/" + playername);
		
		StringBuilder result = new StringBuilder();
		
		readData(output, result);
		
		String u = result.toString();
		
		String uuid = "";
		
		for(int i = 0; i <= 31; i++) {
			if(i >= u.length())
				break;

			uuid = uuid + u.charAt(i);
			if(i == 7 || i == 11 || i == 15 || i == 19) {
				uuid = uuid + "-";
			}
		}
		
		return UUID.fromString(uuid);
	}
	
	private static void readData(String toRead, StringBuilder result) {
		int i = 7;
		
		while(i < 200) {
			if(i >= toRead.length())
				break;

			if(!String.valueOf(toRead.charAt(i)).equalsIgnoreCase("\"")) {
				
				result.append(String.valueOf(toRead.charAt(i)));
				
			} else {
				break;
			}
			
			i++;
		}
	}
	
	private static String callURL(String URL) {
		StringBuilder sb = new StringBuilder();
		URLConnection urlConn = null;
		InputStreamReader in = null;
		try {
			URL url = new URL(URL);
			urlConn = url.openConnection();
			
			if (urlConn != null) urlConn.setReadTimeout(60 * 1000);
			
			if (urlConn != null && urlConn.getInputStream() != null) {
				in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
				BufferedReader bufferedReader = new BufferedReader(in);
				
				if (bufferedReader != null) {
					int cp;
					
					while ((cp = bufferedReader.read()) != -1) {
						sb.append((char) cp);
					}
					
					bufferedReader.close();
				}
			}
			
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
 
		return sb.toString();
	}
}
@@ -219,16 +219,42 @@
 .UUID;%0A%0A
+import org.bukkit.Bukkit;%0A
 import o
@@ -278,16 +278,16 @@
 Player;%0A
-
 %0A/**%0A * 
@@ -549,17 +549,17 @@
 m player
-n
+N
 ame The 
@@ -668,15 +668,199 @@
 ayer
-name) %7B
+Name) %7B%0A%09%09// First check if the player is online%0A%09%09for (Player player : Bukkit.getOnlinePlayers()) %7B%0A%09%09%09if (player.getName().equals(playerName)) %7B%0A%09%09%09%09return player.getUniqueId();%0A%09%09%09%7D%0A%09%09%7D%0A%09%09
 %0A%09%09S
@@ -941,17 +941,17 @@
 + player
-n
+N
 ame);%0A%09%09

Check for online players first before making a request