hugo4715
6/16/2016 - 10:34 AM

Title.java

package fr.hugo4715.crackedskywars.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

import org.bukkit.ChatColor;
import org.bukkit.entity.Player;

import com.google.gson.Gson;

import fr.hugo4715.crackedskywars.SkyWars;
import fr.hugo4715.crackedskywars.util.Reflection.MethodInvoker;

/**
 * @author Hugo4715
 */
public class Title {

	private static Title instance;

	public static Title getInstance(){
		return instance == null ? instance = new Title() : instance;
	}

	private Class<?> classIBaseComponenent;
	private Class<?> classPacketPlayOutTitle;
	private MethodInvoker methodAChatSerializer;
	
	private Constructor<?> titleConstructor;
	
	private Gson gson;
	
	private  Title() {
		classIBaseComponenent = Reflection.getClass("{nms}.IChatBaseComponent");
		classPacketPlayOutTitle = Reflection.getClass("{nms}.PacketPlayOutTitle");
		try {
			titleConstructor = classPacketPlayOutTitle.getConstructor(classPacketPlayOutTitle.getDeclaredClasses()[0],Reflection.getClass("{nms}.IChatBaseComponent"), int.class, int.class, int.class);
		} catch (NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		}
		
		
		try {
			Class<?> classChatSer= classIBaseComponenent.getDeclaredClasses()[0];
			
			for(Field f : classChatSer.getDeclaredFields()){
				SkyWars.get().getLogger().info("name: " + f.getName());
			}
			
			Field f = classChatSer.getDeclaredField("a");
			f.setAccessible(true);
			gson = (Gson) f.get(null);
		} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Send a title to player
	 * @param players Players to send the title to
	 * @param text The text displayed in the title
	 * @param fadeInTime The time the title takes to fade in
	 * @param showTime The time the title is displayed
	 * @param fadeOutTime The time the title takes to fade out
	 * @param color The color of the title
	 * @param action A String representing the EnumTitleAction field (TITLE/SUBTITLE) 
	 */
	public void sendTitle(String text, String action,int fadeInTime, int showTime, int fadeOutTime, ChatColor color,Player[] players)
	{
		try{
			Object chatTitle = gson.fromJson("{\"text\": \"" + text + "\",color:" + color.name().toLowerCase() + "}", classIBaseComponenent);

			
			Object packet = titleConstructor.newInstance(classPacketPlayOutTitle.getDeclaredClasses()[0].getField(action).get(null), chatTitle, fadeInTime, showTime, fadeOutTime);

			for(Player p : players){
				PacketUtil.getInstance().sendPacket(p,packet);

			}
		}catch (Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void sendTitle(String text, String action,int fadeInTime, int showTime, int fadeOutTime, ChatColor color,Player player){
		sendTitle(text, action, fadeInTime, showTime, fadeOutTime, color, new Player[]{player});
	}


	
}