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

import java.util.Collection;
import java.util.List;

import net.mc_pandacraft.java.plugin.pandacraftutils.PandacraftUtils;
import net.mc_pandacraft.java.plugin.pandacraftutils.config.ConfigManager;
import net.mc_pandacraft.java.plugin.pandacraftutils.config.elements.AutoMessagesConfigEntry;
import net.mc_pandacraft.java.plugin.pandacraftutils.players.OnlinePlayer;
import net.mc_pandacraft.java.plugin.pandacraftutils.players.OnlinePlayerManager;

import org.bukkit.scheduler.BukkitRunnable;

public class AutoMessagesManager extends BukkitRunnable {
	private PandacraftUtils plugin = PandacraftUtils.getInstance();

	
	
	public AutoMessagesManager()
	{
        plugin.getServer().getScheduler().runTaskTimer(plugin, this, 0L, 20L);
	}
	
	
	
	
	
	@Override
	public void run() {
		List<AutoMessagesConfigEntry> messages = ConfigManager.getInstance().autoMessagesConfig.getAutoMessages();
		int interval_default = ConfigManager.getInstance().defaultConfig.autoMessages_defaultInterval,
				interval_players = ConfigManager.getInstance().defaultConfig.autoMessages_playerInterval;
		// message
		// permissions
		
		Collection<OnlinePlayer> oPlayers = OnlinePlayerManager.getAll();
		
		
		for (OnlinePlayer op : oPlayers) {
			
			int interval_sec = op.isGuest() ? interval_default : interval_players;
			
			op.firstAutomessageCkeck(interval_sec);
			
			// on vérifie si il est temps, ou non, d'afficher un message aux joueurs
			if (op.getAutomessage_last_message_time() + (interval_sec*1000) > System.currentTimeMillis())
				continue;
			
			// ici, il se peut que id == -1
			int id = op.getAutomessage_last_message_id();
			boolean atLeastOnePermitted = true;
			int c = 0;
			
			// on cherche le prochain message à afficher
			do {
				id++;
				c++;
				if (id >= messages.size()) id = 0;
				if (c > messages.size()) { // il parcouru au moins tout le tableau, sans trouver de message qu'il peut afficher
					atLeastOnePermitted = false;
					break;
				}
			} while(!messages.get(id).hasPlayerPermission(op));
			
			// affichage du message
			if (atLeastOnePermitted) {
				op.setAutomessage_last_message_id(id);
				
				op.sendMessageFromServer(messages.get(id).getMessage());
			}
			
			op.updateAutomessage_last_message_time();
			
		}

	}
	
	
	
}
