package net.mc_pandacraft.java.plugin.pandacraftutils.system_analyzer;

import java.util.LinkedList;

import net.mc_pandacraft.java.plugin.pandacraftutils.PandacraftUtils;

public class TPSAnalyser implements Runnable {
	private static int nb_tick_history = 20 * 20; // 20 secondes;
	
	private PandacraftUtils plugin;

	private LinkedList<Long> tps_times = new LinkedList<Long>();


	public TPSAnalyser(PandacraftUtils pl)
	{
		plugin = pl;
        plugin.getServer().getScheduler().runTaskTimer(plugin, this, 1L, 1L);
	}
	
	
	
	// mise à jour automatique pour le calcul des TPS
	@Override
	public void run() {
		tps_times.add(new Long(System.currentTimeMillis()));
		
		while (tps_times.size() > nb_tick_history + 1)
			tps_times.poll();
		
	}
	
	
	public double getTPS()
	{
		return getTPS(nb_tick_history);
	}
	
	public double getTPS(int nb_tps)
	{
		if (tps_times.size() < 2)
			return Double.NaN;
		
		if (nb_tps >= tps_times.size()) nb_tps = tps_times.size()-1;
		
		long time = tps_times.get(nb_tps).longValue() - tps_times.get(0).longValue();
		
		if (time == 0)
			return Double.NaN;
		
		return nb_tps * 1000 / (double)time;
	}
	
	
	public double[] getTPSHistory(int nb_tick)
	{
		if (nb_tick >= tps_times.size()) nb_tick = tps_times.size()-1;
		
		double[] history = new double[nb_tick];
		
		for (int i=0; i<nb_tick; i++)
		{
			long elapsed = tps_times.get(i+1).longValue() - tps_times.get(i).longValue();
			if (elapsed <= 0) elapsed = 1;
			history[i] = 1000.0 / elapsed;
		}
		
		return history;
	}
	
	
	public String getStringTPSHistory(int nb_tick)
	{
		double[] history = getTPSHistory(nb_tick);
		String s = "{MineAdmin_Graph}{";
		boolean first = true;
		for(double d : history)
		{
			if (first) first = false; else s = s.concat(",");
			s = s.concat((Math.round(d*100)/100D)+"");
		}
		
		s = s.concat("}");
		return s;
	}

}
