package cn.citycraft.JoinMessage.listen;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

import cn.citycraft.JoinMessage.Main;
import fr.xephi.authme.events.LoginEvent;

public class PlayerJoin implements Listener {

	Main plugin;

	String[] lines;

	Player p;

	public PlayerJoin(Main main) {
		plugin = main;

	}

	// Message:
	// - joinmessage.vip:
	// - '%name%'
	// - '%displayname%'
	// - joinmessage
	// - vip

	@EventHandler(priority = EventPriority.HIGHEST)
	public void onJoin(PlayerJoinEvent e) {
		if (e.getJoinMessage() == null) {
			return;
		}
		if (plugin.authme) {
			return;
		}
		e.setJoinMessage(null);
		Player p = e.getPlayer();
		this.sendJoinMessage(p);
	}

	@EventHandler(priority = EventPriority.HIGHEST)
	public void onLogin(LoginEvent e) {
		Player p = e.getPlayer();
		this.sendJoinMessage(p);
	}

	void sendJoinMessage(Player p) {
		String pn = p.getName();
		String pdn = p.getDisplayName();
		List<Map<?, ?>> perms = plugin.getConfig().getMapList("Message");
		for (Map<?, ?> smp : perms) {
			for (Entry<?, ?> key : smp.entrySet()) {
				String permission = (String) key.getKey();
				if (p.hasPermission(permission)) {
					String[] msg = ((ArrayList<?>) key.getValue())
							.toArray(new String[0]);
					for (String message : msg) {
						message = message.replaceAll("%name%", pn)
								.replaceAll("%displayname%", pdn)
								.replaceAll("&", "§");
						Bukkit.broadcastMessage(message);
					}
				}
			}
		}
	}

}
